オブジェクトを継承するにはどうすればよいですか?
function inherit(o){ // inherit is called Object.create in modern implementations
var F= function(){};
F.prototype=o;
return new F();
}
var parent = {
name: "Josh",
print: function(){
console.log("Hello, "+this.name);
}
};
parent.print(); // Hello, Josh
var child = inherit(parent);
child.name = "Jeremy";
parent.print(); //Hello, Josh
child.print(); //Hello, Jeremy
どうすれば親の財産を見ることができますか?
console.log(child.__proto__.name); //won't work in IE; also see getPrototypeOf
どうすれば親の機能にアクセスできますか?
Object.getPrototyepeOf(child).print(); // or
child.print.apply(parent) //functions are just objects, and 'this' pointer can point to wherever you want
どうすれば親の関数を上書きできますか?
child.print = function(){
console.log("Hi ", this.name);
}
parent.print(); //Hello, Josh
child.print(); //Hi, Jeremy
オブジェクトは2つのオブジェクトをどのように継承できますか?
//in chain?
grandchild = inherit(child);
//otherwise, there's no way.
grandchild.name = "Eddie";
grandchild.print();
こちらもご覧ください: