相关疑难解决方法(0)

原型继承 - 写作

所以我有这两个例子,来自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 inheritance prototype

130
推荐指数
2
解决办法
1万
查看次数

标签 统计

inheritance ×1

javascript ×1

prototype ×1