所以我有这两个例子,来自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中创建了这段代码:
function Shape() {}
Shape.prototype.name = "Shape";
Shape.prototype.toString = function() {
result = [];
if(this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
}
function twoDShape() {};
twoDShape.prototype = new Shape();
twoDShape.prototype.constructor = twoDShape;
twoDShape.uber = twoDShape.prototype;
twoDShape.name = "twoD Shape";
var a = new twoDShape();
console.log(a.toString());
Run Code Online (Sandbox Code Playgroud)
我不知道为什么但是当我运行它时,firefox就冻结了.我一直在努力解决这个问题.我的猜测是我的代码中应该有一个无限循环,并且它存在于if条件的某个地方,但我没有找到它.有人可以帮我解决这个问题.谢谢!