[英]How can I access a property of a constructor through an instance of that constructor?
Here the constructor is Animal.这里的构造函数是 Animal。 It has two instances duck and beagle.
它有两个实例duck 和beagle。 There is a function named eat() which is actually a prototype of Animal.
有一个名为eat() 的function 实际上是Animal 的原型。
function Animal() {
this.color = "brown";
}
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
let duck = Object.create(Animal.prototype);
let beagle = Object.create(Animal.prototype);
duck.eat();
console.log(duck.color);
here这里
duck.eat()
works, but duck must also inherit the color brown right?有效,但鸭子也必须继承棕色,对吗? Why am I not able to access it using
为什么我无法使用它访问它
duck.color ?
There is no color
property on Animal.prototype
. Animal.prototype
上没有color
属性。 It is dynamically added to the object when the constructor function is called… but you aren't calling the constructor function at all.当构造函数 function 被调用时,它被动态添加到 object 中……但你根本没有调用构造函数 function。
If you want to create an instance of a class, then call the constructor function.如果要创建 class 的实例,则调用构造函数 function。 Don't use
Object.create
.不要使用
Object.create
。
function Animal() { this.color = "brown"; } Animal.prototype = { eat: function() { console.log("nom nom nom"); } }; let duck = new Animal(); let beagle = new Animal(); duck.eat(); console.log(duck.color);
No It wont inherit,不,它不会继承,
Please read the definition of Object.create
.请阅读
Object.create
的定义。
"The Object.create() method creates a new object, using an existing object as the prototype of the newly created object" “Object.create() 方法创建一个新的 object,使用现有的 object 作为新创建对象的原型”
Means, only prototype will be copied from existing object on will be placed in newly create object's prototype
意味着,只有
prototype will be copied from existing object on will be placed in newly create object's prototype
Here color
is instance variable not prototype.这里
color
是实例变量而不是原型。 Hence wont be available in newly created duck
object.因此在新创建的
duck
object 中将不可用。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.