我正在学习 CodeAcademy JS 练习并且对这个例子有疑问:
//Animal class
function Animal(name) {
this.name = name;
}
//Attach sayName method to Animal class
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
//create an animal object instance
var dog = new Animal('Barker');
//invoke a method attached to the prototype from the object instance
dog.sayName();
我对这段代码的理解是:
由于在调用函数
Animal()
之前使用了 new 关键字,sayName()
方法: Animal.prototype.sayName = function()
sayName()
附加到类 prototype
,该方法现在可用于通过使用 Animal
函数构造函数 new Animal()
类创建的任何对象这是对这段代码发生的事情的正确理解吗?
另外,我试图了解
this
如何指向 this.name
中的 Animal 对象:Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
Animal.prototype
不是指向一个实际的对象:这个 prototype
对象实例的 Animal
对象吗?如果是这样,不应该 this
中的 this.name
指向 Animal.prototype
,因为 sayName()
实际上是从 Animal.prototype
调用的?我对
this
上下文的理解是 this
总是指向调用函数的对象。但是,在这种情况下,当 dog.sayName()
被调用时, this
指向 Animal
,这就是 this.name
在记录到控制台时等于 'Barker'
的方式。我猜要么是我误解了 Animal.prototype 指向原型(prototype)对象,要么是 JS 在将方法附加到
dog.sayName()
的上下文中正在“幕后”做一些事情来将 this
与 prototype
相关联。在这个小例子中有多个问题,但准确掌握这里发生的事情将真正有助于我理解这些基本概念。
最佳答案
是的,听起来你理解它。
是的,prototype
对象是一个 Object
实例。
不,因为您将其称为 dog
的方法。
dog.sayName();
如果你这样称呼它,那么是的,
this
会引用 Animal.protoype
。Animal.protoype.sayName();
但这不会很有用。
不完全的。在大多数情况下,
this
指的是调用该方法的对象,而不是它所属的对象。一个方法实际上可以是多个对象的一个属性,因此 this
动态地指向它作为方法调用的对象。当然,
this
可以在其他上下文中引用其他事物,例如未作为方法调用时,或在使用 .bind
的绑定(bind)函数中。关于JavaScript 构造函数、原型(prototype)附加方法和 'this',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36521166/