gpt4 book ai didi

javascript - 在子对象内定义函数时的 "this"范围

转载 作者:行者123 更新时间:2023-11-28 08:33:48 25 4
gpt4 key购买 nike

我正在使用有关页脚的自定义选项扩展主干 View ,我在另一个类中对其进行了评估。

看起来像:

var EditUserView = Backbone.View.extend({
footer: {
name: "Hello",
label: function() {
//Return "Create" if it's a new model without id, or else "Save"
return this.model.id ? "Save" : "Create";
}
}
});

如您所见,属性应该能够定义为返回字符串的函数或普通字符串值。我使用 _.result 评估 FooterView 中的这些选项:

initialize: function(options) {
//"options" is the footer-object from the view.
this.data = {
name: _.result(options, "name"),
label: _.result(options, "label")
};
}

但问题是我无法访问上面定义的标签函数内的 EditUserView 的 this 。我也无法定义一个 var that = this 因为我正在扩展对象,但没有地方放置局部变量。如何使我在页脚对象中定义的函数具有 UserEditView 的 this 范围?

我也可以接受:

footer: {
name: "Hello",
label: this.getName
},

getName: function() {
return this.model.id? "Save":"Create";
}

如果其他方式不可行或者这种方式更容易实现。

最佳答案

一般来说,函数内的 this 仅取决于函数的调用方式(当然,除非您有绑定(bind)函数)。鉴于此:

var V = Backbone.View.extend({
m: function() { console.log(this) }
});
var v = new V;

然后这些做不同的事情:

var f = v.m; f();
v.m();

它们调用相同的函数,但在第一种情况下 this 将是全局对象,在第二种情况下它将是 v;区别不在于函数本身,区别在于调用方式。

如果我们看 _.result ,我们可以看到它是如何调用该函数的:

_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};

注意 call在那里,这意味着 _.result(obj, 'm') 是,如果 mobj 的函数属性,则与说的一样:

obj.m()

将其应用到您的:

_.result(options, "label")

我们看到您实际上是在说:

options.label()
label 函数中的

this 将是 options

我在上面提到了绑定(bind)函数。创建绑定(bind)函数的官方方法是使用 Function.prototype.bind :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

这意味着您可以使用 bind 来指定函数内的 this 内容,无论函数是如何调用的。您还可以使用_.bind , _.bindAll , $.proxy ,以及用于模拟函数上的 native bind 方法的各种其他方法。

在 View 的initialize中,您可以将footer中的函数绑定(bind)到适当的this。但请注意,您必须克隆整个 footer 以避免意外地通过原型(prototype)共享内容:

initialize: function() {
var footer = {
name: this.footer.name,
label: this.footer.label.bind(this)
};
this.footer = footer;
}

使用 _.clone 的任意组合以明显的方式进行概括, _.isFunction ,迭代器会让你高兴。

这样做的缺点是, View 的每个实例都会获得自己独特的 footer 副本,如果您有很多实例或者 footer,这可能会造成浪费。很大。如果这是一个问题,那么您可以编写自己的 _.result 版本,如下所示(未经测试的代码):

_.mixin({
i_cant_think_of_a_good_name_for: function(object, property) {
if(object == null)
return void 0;
return _.isFunction(property) ? property.call(object) : property;
}
});

然后说:

_.i_cant_think_of_a_good_name_for(this, options.name);
_.i_cant_think_of_a_good_name_for(this, options.label);

在你看来。请注意,这里的第一个参数是您希望用于该函数的 this,第二个参数是整个属性而不仅仅是其名称。

关于javascript - 在子对象内定义函数时的 "this"范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com