相关疑难解决方法(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万
查看次数

JavaScript继承和构造函数属性

请考虑以下代码.

function a() {}
function b() {}
function c() {}

b.prototype = new a();
c.prototype = new b();

console.log((new a()).constructor); //a()
console.log((new b()).constructor); //a()
console.log((new c()).constructor); //a()
Run Code Online (Sandbox Code Playgroud)
  • 为什么不为b和c更新构造函数?
  • 我做遗传错了吗?
  • 更新构造函数的最佳方法是什么?

此外,请考虑以下内容.

console.log(new a() instanceof a); //true
console.log(new b() instanceof b); //true
console.log(new c() instanceof c); //true
Run Code Online (Sandbox Code Playgroud)
  • 鉴于这(new c()).constructor等于a()Object.getPrototypeOf(new c())a{ },怎么可能instanceof知道这new c()是一个实例c

http://jsfiddle.net/ezZr5/

javascript inheritance constructor instanceof

36
推荐指数
3
解决办法
9428
查看次数