我正在研究 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();
我对这段代码的理解是:
- 由于在调用函数之前使用了 new 关键字,JS 创建了一个新的 Animal 对象实例,var dog 指向该实例
Animal()- 函数构造函数 - var dog 对象的原型
sayName()在以下行中附加了方法:Animal.prototype.sayName = function() - 由于
sayName()已附加到类prototype,因此该方法现在可用于Animal通过使用new Animal()函数构造函数从类创建的任何对象
这是对这段代码发生的事情的正确理解吗?
另外,我试图了解如何this指向 Animal 对象this.name:
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
不Animal.prototype指向一个实际的对象:prototype这个Animal对象实例的对象?如果是这样,不应该指向, 因为this实际上是从?this.nameAnimal.prototypesayName()Animal.prototype
我对上下文的理解this是它this总是指向调用函数的对象。但是,在这种情况下,whendog.sayName()被调用,this指向Animal,这就是当它被记录到控制台时的this.name相等性。'Barker'我猜要么我误解了 Animal.prototype 指向原型对象,要么 JSdog.sayName()在this将方法附加到prototype.
在这个小例子中有多个问题,但准确掌握这里发生的事情将真正有助于我理解这些基本概念。