所以我有这两个例子,来自javascript.info:
例1:
var animal = {
eat: function() {
alert( "I'm full" )
this.full = true
}
}
var rabbit = {
jump: function() { /* something */ }
}
rabbit.__proto__ = animal
rabbit.eat()
Run Code Online (Sandbox Code Playgroud)
例2:
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)
从示例2开始:当代码到达时 …
可能重复:
Javascript多重继承
有没有办法在JavaScript中执行此操作:
Foo = function() {
};
Bar = function() {
};
Baz = function() {
Foo.call(this);
Bar.call(this);
};
Baz.prototype = Object.create(Foo.prototype, Bar.prototype);
var b = new Baz();
console.log(b);
console.log(b instanceof Foo);
console.log(b instanceof Bar);
console.log(b instanceof Baz);
Run Code Online (Sandbox Code Playgroud)
那么Baz既是Foo又是Bar的一个例子?
javascript inheritance prototype multiple-inheritance ecmascript-5
我知道如何在javascript中继承,但我只能继承一个对象.例如.
function fun1() {
this.var1=10;
this.meth1=function() {
...
...
};
}
function fun2() {
this.var2=20;
this.meth2=function() {
...
...
};
}
function fun3() {
this.var3=30;
this.meth3=function() {
...
...
};
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想要一个fun3对象继承fun1对象我可以做到这一点
fun3.prototype=new fun1();
Run Code Online (Sandbox Code Playgroud)
或者继承fun2对象我可以做到这一点
fun3.prototype=new fun2();
Run Code Online (Sandbox Code Playgroud)
但我怎么能继承fun1和fun2?