Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.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 在JS中,为什么要在其原型&x27;谁的财产不同?_Javascript_Inheritance_Properties_Prototype - Fatal编程技术网

Javascript 在JS中,为什么要在其原型&x27;谁的财产不同?

Javascript 在JS中,为什么要在其原型&x27;谁的财产不同?,javascript,inheritance,properties,prototype,Javascript,Inheritance,Properties,Prototype,派生对象可以从其原型对象中获取属性值; 但当设置该属性时,它将在派生对象中添加新属性。 更多信息请参见下面的代码 function Base(name) {this.name = name }; function Deriver(name) {this.dname = name }; var base = new Base('base'); Deriver.prototype = base ; d1 = new Deriver('d1'); console.log(d1.name);

派生对象可以从其原型对象中获取属性值; 但当设置该属性时,它将在派生对象中添加新属性。 更多信息请参见下面的代码

function Base(name) {this.name  = name };

function Deriver(name) {this.dname  = name };
var base = new Base('base');
Deriver.prototype = base  ;


d1 = new Deriver('d1');
console.log(d1.name);  // it will show "base". That'ok.



d1.name = "new name"; // !!! it does not update the property from its protoype object
                      // it add new property "name" in the object d1. 
console.log(d1.name); // it will show "new name" 
console.log(base.name); // it still show "base"

它将属性直接放在
d1
上,因为这是放置属性的位置。为什么你会期望它把它放在原型链的下游?属性可以将同名的属性隐藏在链的下游。嗨,疯狂,你是对的,我问错了问题。这个问题实际上来自C++和JS之间的比较继承。C++中的继承,SubBobe可以从基础对象访问属性,既可以获取GET也可以设置SET(当然是公共/受保护的属性)。在JS中,子对象只能从prototype对象中获取属性,set会在其本地添加新属性,这让我很困惑。现在我明白了基于原型的继承不同于基于类的继承。你的问题让我思考他们之间的区别,并最终理解了这一点。非常感谢。不客气,你是对的,基于类的继承是完全不同的。原型继承只不过是对象的“查找链”。