Javascript this关键字和变量指向一个对象方法

Javascript this keyword and variables pointing to an object method

本文关键字:一个对象 方法 变量 this 关键字 Javascript      更新时间:2023-09-26

我想了解this关键字在这种情况下是如何工作的。

function Person(name) {
    this.name = name;
    this.sayName = function() {
        alert('My name is ' + this.name);
    };
}

var p = new Person('Smith');
p.sayName();  // 'My name is Smith'
var q = p;
q.sayName();  // 'My name is Smith'
q = p.sayName;
q();  // 'My name is'   ???

为什么最后一个例子没有提到'Smith'?

是否因为q只是指向一个函数(即该方法所属的对象在此上下文中不被识别)?因为q是在全局空间,this是全局的函数内(即sayName()的调用者是全局空间或窗口)?

这是因为this引用了调用函数的上下文。当您执行p.sayName()时,上下文是p。如果你只是调用一个没有上下文的函数,它将默认为全局上下文(通常是window)或严格模式下的undefined

如果你想让它按照你期望的方式工作,你可以将this绑定到p,这样q():

q = p.sayName.bind(p);
q(); // My name is Smith

借助@Paulpro所说的,您可以通过在类中添加var that = this;来创建对Person()上下文的引用。这样就可以从函数内部调用that.name

function Person(name) 
{
    var that = this;
    this.name = name;
    this.sayName = function() 
    {
        alert('My name is ' + that.name);
    };
}

var p = new Person('Smith');
p.sayName();  // 'My name is Smith'
var q = p;
q.sayName();  // 'My name is Smith'
q = p.sayName;
q();  // 'My name is Smith'


< 视图jsFiddle演示/em>