Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/479.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 覆盖和扩展原型_Javascript - Fatal编程技术网

Javascript 覆盖和扩展原型

Javascript 覆盖和扩展原型,javascript,Javascript,当我用一个对象(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

当我用一个对象(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

这对我来说似乎很明显-每个对象都有一个对其原型的引用,该引用是在首次构建对象时设置的。如果将原型设置为新的对象:

Gadget.prototype = {price: 100};
您尚未更改对旧原型的任何引用。只有后来创建的对象才会将其原型设置为新值


想象一下这两者之间的区别:

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

谢谢,我知道了这个概念,但是我说不清楚。你的解释很清楚。