繁体   English   中英

为什么greet函数不返回预期值?

[英]Why does the greet function not return the expected value?

题:

为什么greet函数不返回预期值?

码:

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

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + name;
}

我该如何回答这个问题? 我创造了一个新人,那我该怎么办?

var John = new Person("John");

错误的访问方法。 未定义变量name ,仅定义this.name 所以它看起来在功能范围称为变量name ,而不是对象调用的属性name

要从对象中访问对象的属性,我们使用this关键字。 因此,我们需要使用this.name来访问下面实现中的name属性。

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + this.name;
}

在你的代码中:

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

当作为构造函数调用时,上面将创建名为name的实例的命名属性,并为其指定name参数的值。

> Person.prototype.greet = function(otherName){
>     return "Hi" + otherName + ", my name is " + name;
> }

这里标识符名称用作变量,但您要查找的标识符是实例的命名属性,因此您需要在此处访问它。 通常,该函数将被称为实例的方法,以便函数内将所述实例的引用。 所以你要:

      return "Hi" + otherName + ", my name is " + this.name;

所以现在你可以这样做(请注意,以大写字母开头的变量按惯例保留给construtors):

> var john = new Person("John");

然后:

john.greet('Fred');

因为greet被称为john的方法,它将返回:

Hi Fred, my name is John

或者,由于这是范围继承的问题(第二个函数无法访问变量“name”),我们可以将代码重新编写为如下所示,将其全部包含在Person函数下:

function Person(name){
   this.name = name;
   this.greet = function(otherName){
      return "Hi" + otherName + ", my name is " + name;
    }
}

也适用。

您需要更改greet函数以使用this关键字来使用对象的名称:

Person.prototype.greet = function(otherName){
     return "Hi" + otherName + ", my name is " + this.name;
}

之后,只需致电John.greet("other name");

请尝试以下方法:

function Person(name){
   this.name = name;
   this.greet = function(otherName){
      return "Hi " + otherName + ", my name is " + name;
    }
} 

Person("Joe")
greet("Kate")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM