JavaScript原型继承链:“;那";访问上层属性和方法的技术?
当使用原型继承时,我需要访问原型链上一级的属性和方法 这是一种可以接受的技术吗JavaScript原型继承链:“;那";访问上层属性和方法的技术?,javascript,inheritance,super,chain,prototypal,Javascript,Inheritance,Super,Chain,Prototypal,当使用原型继承时,我需要访问原型链上一级的属性和方法 这是一种可以接受的技术吗 function Cheese() { this.weight = 100; this.unit = 'g'; this.that = this; // not sure about this... does it create a circular reference? } Cheese.prototype.setWeight = function(myWeight) { this
function Cheese() {
this.weight = 100;
this.unit = 'g';
this.that = this; // not sure about this... does it create a circular reference?
}
Cheese.prototype.setWeight = function(myWeight) {
this.weight = myWeight;
}
var cheese = new Cheese();
var myCheddar = Object.create(cheese); // http://javascript.crockford.com/prototypal.html
myCheddar.setWeight(500);
console.log(myCheddar.weight + myCheddar.unit); //-> 100kg
console.log(myCheddar.that.weight + myCheddar.unit); //-> 500g
看起来像
Object.getPrototypeOf
这就是答案
我不明白您想做什么-代码中没有“继承”或扩展设置,因此所有属性都可以在主级别访问。您是否试图访问原型而不是实例上的属性?@jrade有继承-请参阅
Object.create()
行…这不是继承,如果我正确阅读了那篇文章,那只是创建cheese
变量的克隆。但最重要的是,javascript中没有继承,除了所有内容都继承自对象
原型之外。@jrade否,对象.create()
创建一个新对象,使该新对象将传入的对象作为其原型。好吧,那又怎样,他想访问原型而不是实例上的属性?那还不是遗产。