Javascript 将 this 绑定到对象外部的函数
Javascript bind this to a function outside object
我已经阅读了有关在对象外部的函数内使用绑定访问 this
的信息,但由于某些原因我无法做到这一点。
function test (len){
return this.length - len;
}
var SETTINGS = {
length : 21,
trimmed: test.bind(this,5),
x: function(){
return this.length;
}
};
SETTINGS.x(); // this is available.
SETTINGS.trimmed(); //len is 5 but this is Window.
可能跟我对bind的理解有关系
发生这种情况是因为在您绑定 this
时它指向 window
对象。这有点棘手,但在 JS 中,仅仅因为 this
在一个对象中,它 不会自动成为对象 。它更像是:this
指向 window 除非应用了某些规则 。
您可能会问什么规则?来自精彩的丛书 You Don't Know JS:
Determining this
Now, we can summarize the rules for determining this from a function
call's call-site, in their order of precedence. Ask these questions in
this order, and stop when the first rule applies.
Is the function called with new
(new binding)? If so, this is the
newly constructed object.
var bar = new foo()
Is the function called with call
or apply
(explicit binding), even
hidden inside a bind hard binding? If so, this is the explicitly
specified object.
var bar = foo.call( obj2 )
Is the function called with a context (implicit binding), otherwise
known as an owning or containing object? If so, this is that context
object.
var bar = obj1.foo()
- that is why SETTINGS.x();
works btw.
Otherwise, default the this (default binding). If in strict mode, pick
undefined, otherwise pick the global object.
var bar = foo()
- your case
您的情况适用默认规则。
注意 ES6 arrow functions,因为它们会自动绑定 this
(就像 bind
)。
我已经阅读了有关在对象外部的函数内使用绑定访问 this
的信息,但由于某些原因我无法做到这一点。
function test (len){
return this.length - len;
}
var SETTINGS = {
length : 21,
trimmed: test.bind(this,5),
x: function(){
return this.length;
}
};
SETTINGS.x(); // this is available.
SETTINGS.trimmed(); //len is 5 but this is Window.
可能跟我对bind的理解有关系
发生这种情况是因为在您绑定 this
时它指向 window
对象。这有点棘手,但在 JS 中,仅仅因为 this
在一个对象中,它 不会自动成为对象 。它更像是:this
指向 window 除非应用了某些规则 。
您可能会问什么规则?来自精彩的丛书 You Don't Know JS:
Determining this
Now, we can summarize the rules for determining this from a function call's call-site, in their order of precedence. Ask these questions in this order, and stop when the first rule applies.
Is the function called with
new
(new binding)? If so, this is the newly constructed object.
var bar = new foo()
Is the function called with
call
orapply
(explicit binding), even hidden inside a bind hard binding? If so, this is the explicitly specified object.
var bar = foo.call( obj2 )
Is the function called with a context (implicit binding), otherwise known as an owning or containing object? If so, this is that context object.
var bar = obj1.foo()
- that is whySETTINGS.x();
works btw.Otherwise, default the this (default binding). If in strict mode, pick undefined, otherwise pick the global object.
var bar = foo()
- your case
您的情况适用默认规则。
注意 ES6 arrow functions,因为它们会自动绑定 this
(就像 bind
)。