javascript - 重写和扩展原型(prototype)

标签 javascript

我不知道为什么当我用一个对象覆盖下面的原型(prototype)时(Gadget.prototype = { Price: 100;},只有 Gadget(theGadget) 的新实例才能访问新属性。

但是扩展时(Gadget.prototype.price = 100)所有实例都可以访问。

function Gadget(name, color) {
this.name = name;
this.color = color;
this.brand = "Sony";
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
    }
}

myGadget = new Gadget();

myGadget.brand;


//Gadget.prototype.price = 100;

Gadget.prototype = {
 price: 100,
 rating: 3,

};

myGadget.price;
theGadget = new Gadget();
theGadget.price

最佳答案

这对我来说似乎很明显 - 每个对象都有一个对其原型(prototype)的引用,该原型(prototype)是在第一次构造对象时设置的。如果您将原型(prototype)设置为新的东西:

Gadget.prototype = {price: 100};

您尚未更改对旧原型(prototype)的任何引用。只有后来创建的对象才会将其原型(prototype)设置为新值。


把它想象成这之间的区别:

var a = {foo: true};
var b = a;
a = {baz: 'quux'}; // b refers to the original value of a

还有这个:

var a = {foo: true};
var b = a;
a.baz = 'quux'; // a and b refer to the same object

关于javascript - 重写和扩展原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7542036/

相关文章:

c# - 使用 Ajax 在 C# 中添加 session 变量

javascript - 如何在 JavaScript 中添加 Google 登录?

javascript - 如何将 setInterval 转换为 requestAnimationFrame

javascript - 表单提交处理程序未被调用

javascript - 函数执行完成之前执行的回调

javascript - 使用 chrome 的单个用户不会出现导航菜单

javascript - 为什么模板版本 1+ 从 HTML 按钮中删除类型属性?

javascript - this 和词法作用域

javascript - Jquery Slide 切换问题

javascript - 如何通过ng2-charts angular使用chartJs的自定义渲染方法?