对象原型方法与值

Set*_*hen 0 javascript

我对我的代码发生了什么感到有点困惑,这是我到目前为止所做的:

function Person(name) {
    this.name = name;
}

Person.prototype.getName = this.name;
Person.prototype.displayName = function() {
    return this.name;
}


var Sethen = new Person("Sethen");

console.log(Sethen.getName);
console.log(Sethen.displayName());
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么getName不给我this.name值,只记录空白,而displayName方法给我正确的值. getName是我的原型对象的属性,所以我的思维过程是我可以像这样抓住它.

为什么不getName记录值Sethen?我如何像常规财产一样抓住这些信息?我必须使用方法吗?

And*_*ker 5

因为this运行该代码时,值不是您认为的值.this可能等于全局对象(即window).

由于您displayName通过在前面添加Person对象实例来调用和设置上下文,因此this在函数内部正确设置并获得该人的姓名.

当然,您可以随时name直接访问该属性(Sethen.name).