gpt4 book ai didi

javascript - 无法真正理解 Javascript 中的构造函数和原型(prototype)关系

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:51:55 25 4
gpt4 key购买 nike

我是 Javascript 的初学者,很难理解构造函数和原型(prototype)属性之间的关系。

我知道 Prototype 对象有一个指向构造函数的 constructor 属性。并且构造函数有一个指向原型(prototype)对象的 prototype 属性。

这是我试图理解的代码(我的问题在代码中有注释):

function Car(){};
var myCar = new Car();
console.log(Object.getPrototypeOf(myCar)); //why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ?


var Vehicle = {
getName : function(){
return "hello";
}
};
Car.prototype = Vehicle ; //I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ?
console.log(Object.getPrototypeOf(myCar).getName()); //Why am i getting getName() function does not exist ?

最佳答案

why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ?

这就是 Chrome(或您使用的浏览器)命名对象的方式。如果您仔细查看属性,它确实是 Car.prototype :

enter image description here

I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ?

您不能更改现有对象的原型(prototype),只能扩展它。设置Car.prototype = Vehicle;只会更改 Car future 实例的原型(prototype),现有的仍将引用原始原型(prototype)对象,它没有 getName属性:

// create a new instance after setting the new prototype
var myCar2 = new Car();
// yields false
console.log(Object.getPrototypeOf(myCar) === Object.getPrototypeOf(myCar2));

这实际上与原型(prototype)没有任何关系,而只是赋值和引用在 JavaScript 中的工作方式。假设我有以下对象:

var foo = {
bar: {
answer: 42
}
};

并假设我分配 foo.bar到另一个对象的属性:

var baz = {};
baz.xyz = foo.bar;

设置foo.bar现在改为其他值,例如 foo.bar = {} , 不会改变 baz.xyz 的值, 它仍然会引用之前的对象。

只有扩展原始对象(扩展原型(prototype))或改变它的属性才会有效果,因为这两者,foo.barbaz.xyz引用同一个对象:

foo.bar.answer = 21;
console.log(baz.xyz.answer); // shows 21
// console.log(foo.bar === baz.xyz); // yields true

关于javascript - 无法真正理解 Javascript 中的构造函数和原型(prototype)关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com