我试图找出“this”在我的上一个函数(Mamamal.prototype.haveBaby)中引用的是什么;
var Mammal = function(name){
this.name = name;
this.offspring = [];
};
// var myMammal = new Mammal('Joe');
Mammal.prototype.sayHello = function(){
return 'My name is ' + this.name + ", I'm a Mammal";
};
Mammal.prototype.haveBaby = function(){
debugger;
var childName = "Baby " + this.name;
baby = new this.constructor(childName); //new Cat OR new Mammal
baby.name = childName;
this.offspring.push(baby);
return baby;
};
我不知道为什么语法
baby - new this.constructor(childName);
是this
Mammal.prototype?(然后是构造函数,所以它将是Mammal.prototype.constructor(childName);
这是我知道如何设置构造函数的唯一方法.Mammal.constructor 不起作用。
最佳答案
this
的值取决于如何调用函数,在您的例子中为 Mammal.prototype.haveBaby
。
如果您使用 Mammal.prototype.haveBaby()
调用它,则 this
引用 Mammal.prototype
。
如果您将其称为实例方法(更有可能),例如
var mammal = new Mammal();
var baby = mammal.haveBaby();
那么this
指的是哺乳动物
。
但在这两种情况下,您都访问相同属性,因为 Mammal
的每个实例都继承 Mammal.protoype
的属性。所以 this.constructor === Mammal.prototype.constructor
,无论这两者处于哪种情况。
Read the MDN documentation for more information about this
.
关于javascript - 这有什么值(value)呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201368/