JavaScript方法调用

时间:2013-02-02 10:50:38

标签: javascript

在“JavaScript:The Definitive Guide,第6版”,第61页,第4.5节“调用表达式”一书中,它说 -

  

在方法调用中,作为主题的对象或数组   属性访问权限成为this参数的值   该功能正在执行中。

有人可以用简单的英语解释该陈述的含义,并举一个例子吗? 我特别不知道“主题属性访问”是什么意思。

非常感谢!

3 个答案:

答案 0 :(得分:1)

在JavaScript中(暂时),this如何调用函数决定,而不是函数的定义方式。弗拉纳根说的是,鉴于此:

foo.bar();

...在致电bar期间,this将引用foo引用的对象。

如果您来自其他语言(如Java或C#),您可能会想,“但this foo总是bar”,但事实并非如此JavaScript的。例如:

var f = foo.bar; // Get a reference to the function, but not calling it
f();             // Now we call it

在上文中,对this的调用中的bar foo,它是全局对象(如果您未处于严格模式)或undefined(如果你的话)。

更多(在我的博客上):

答案 1 :(得分:0)

为了补充T.J.的答案,这里是an example

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指的是调用该函数的对象

答案 2 :(得分:0)

我对'this'的理解是'this'是执行过程中函数的上下文 除非您明确地更改'this',否则默认行为是函数执行期间的上下文是函数调用的上下文。

第一种情况(最简单):

var writeHelloFromThis = function() {
       console.log('hello from ' + this);
 };

writeHelloFromThis();

- >输出是“来自[对象窗口]的问候”,因为调用的上下文是全局对象,即Window。

第二种情况:现在我们定义一个对象,并将writeHelloFromThis添加到它:

var anObject={};

anObject.writeHelloFromThis = writeHelloFromThis;

现在我们使用anObject作为上下文调用writeHelloFromThis:

anObject.writeHelloFromThis();

- >输出是“hello from [object Object]”:这是函数调用的上下文:在这种情况下是anObject。

第三种情况,有点棘手:现在我们将把'anObject'的writeHelloFromThis存储到另一个var中:

var anObjectsWriteHelloFromThis = anObject.writeHelloFromThis;

anObjectsWriteHelloFrom这只是存储一个函数(=一个引用)而不知道任何关于'anObject'的信息。所以如果我们打电话:

 anObjectsWriteHelloFromThis();

输出将是“hello from [object Window]”,因为调用的上下文是全局对象,即Window。

最后一句话:如果这种处理方式似乎对你有用,那么你就是对的:这就是为什么一些Function方法:bind,call,apply,允许你改变函数的上下文。

所以最后一个例子:

 writeHelloFromThis.call(anObject);

将输出“hello from [object Object]”,而不是windows,因为在这里我们强制'this'为anObject。