我通过CodeAcademy JS excercises工作,有一个关于这个例子的问题:JavaScript构造函数,原型附加方法,和“这个”
//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();
我这个代码的理解是:
- JS创建一个新的动物对象实例var dog指向作为在调用函数之前使用new关键字的结果
Animal()
- 函数构造函数 - var dog对象的原型具有
sayName()
方法附连到它的行:Animal.prototype.sayName = function()
- 由于
sayName()
附着到类prototype
,该方法现可从Animal
类通过使用new Animal()
功能构造的创建的任何对象
这是正确理解这段代码发生了什么?
另外,我也想了解如何this
指向动物对象this.name
:
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
不Animal.prototype
指向一个实际的对象:此Animal
对象实例的prototype
对象?如果是这样,this
不应该this.name
指向Animal.prototype
,因为sayName()
实际上是从Animal.prototype
被调用?
我对this
的上下文的理解是,this
总是指向调用该函数的对象。但是,在这种情况下,当dog.sayName()
被调用时,this
指向Animal
,这是this.name
等于'Barker'
当它被记录到控制台时。 我在猜测,要么我误解Animal.prototype指向原型对象,要么JS在“幕后”做一些事情,在将方法附加到prototype
的上下文中将dog.sayName()
到this
关联起来。
在这个小例子中有多个问题,但掌握这里发生的事情真的会帮助我理解这些基本概念。
当一个构造函数被调用时,它会将其原型赋值给创建的对象的原型,这样'dog'就可以完全访问'Animal.prototype'的函数和属性。你可以看一下http://qr.ae/RO44Vn以获得关于JS的'this'的详细信息。 – Redu