在第61页第4.5节的"JavaScript:权威指南,第6版“一书中,它写道:
在方法调用中,属性访问的主题的对象或数组在执行函数时成为
this
参数的值。
有人能用通俗易懂的英语解释这句话的意思吗?我尤其不知道“属性访问的subject”是什么意思。
非常感谢!
发布于 2013-02-02 03:19:59
我对“这”的理解是,“这”是函数执行过程中的上下文。
除非您解释地更改了“this”,否则默认行为是函数执行过程中的上下文是函数调用的上下文。
第一种情况(最简单):
var writeHelloFromThis = function() {
console.log('hello from ' + this);
};
writeHelloFromThis();
->输出是"hello from object Window",因为调用的上下文是全局对象,即窗口。
第二个例子:现在我们定义一个对象,并将writeHelloFromThis添加到它中:
var anObject={};
anObject.writeHelloFromThis = writeHelloFromThis;
现在我们用writeHelloFromThis作为上下文调用anObject:
anObject.writeHelloFromThis();
->输出是"hello from Object“:在本例中,这是函数调用的上下文: anObject。
第三种情况,有点棘手:现在我们将把writeHelloFromThis of 'anObject‘存储到另一个var中:
var anObjectsWriteHelloFromThis = anObject.writeHelloFromThis;
anObjectsWriteHelloFromThis只是存储一个函数(=一个引用),而不知道任何关于'anObject‘的信息。所以如果我们打电话:
anObjectsWriteHelloFromThis();
输出将是"hello from object Window",因为调用的上下文是全局对象即窗口。
最后一点:如果这种方式对你来说是有限制的,你是对的:这就是为什么某些函数方法:绑定、调用、应用,允许您更改函数的上下文。
最后一个例子是:
writeHelloFromThis.call(anObject);
将有输出"hello from Object",而不是窗口,因为这里我们强制'this‘为anObject。
发布于 2013-02-02 02:52:30
在JavaScript (目前)中,this
取决于函数的调用方式,而不是函数的定义方式。弗拉纳根的意思是,鉴于这一点:
foo.bar();
...during对bar
的调用,this
将引用foo
引用的对象。
如果您来自其他一些语言,如Java或C#,您可能会认为,“但this
总是在bar
中引用foo
”,但在JavaScript中并非如此。示例:
var f = foo.bar; // Get a reference to the function, but not calling it
f(); // Now we call it
在上面的调用中,对bar
的调用中的bar
是而不是 foo
,它是全局对象(如果没有严格模式)或undefined
(如果是的话)。
更多(在我的博客上):
发布于 2013-02-02 03:02:08
为了补充T.J.的答案,这里是一个例子
var o = {}; // define an object
o.name = 'foo'; // add an attribute to the object
var f = function() { // define a function
return this.name; // the function uses this internally
}
o.someFunction = f; // add the function to the object
var result = o.someFunction();
现在,result
的值是'foo'
,因为函数是在对象o上调用的,而在函数内部,this
引用了调用函数的对象。
https://stackoverflow.com/questions/14661108
复制