java的继承:
class Parent {
}
class Child extends Parent {
}
js的继承:
function Parent() {} function Child() {} Child.prototype=Parent;//Child的原型是Parent,即Child继承于Parent
如果按java的编程思想,是不是感觉应该这样写?实际上是错误的。应该是:Child.prototype=new Parent(); WHY?
var parent = new Parent(); Child.prototype = parent; var c1 = new Child(); c1.__proto__ === parent;//true
new Child()干了什么,为啥会有一个__proto__属性?
创建一个对象,增加一个属性__proto__,c1.__proto__ = Child.prototype。这里要说明一下__proto__这个属性在不同的浏览器中不一定相同。这样通过Child这个函数实例化的每个对象都有一个相同的__proto__属性即parent,形成一个链条,原型链继承也就实现了。
js的继承机制完全和java的不一样,千万不要用java的继承来理解js的继承。可以用key-value来理解,js里的对象都是key-value,__proto__是自动加入的一个key而已,其value即为构造函数的prototype
关于instanceof的理解
function Func() {} var f = new Func(); f instanceof Func;//true
f instanceof Func可以写成:
var L = f, R = Func; while(true) { if(L === null) { return false; } if(L.__proto__ === R.prototype) { return true; } L = L.__proto__; }
这样就好理解了吧,其实就是遍历对象的原型链,看有没有原型对象等于该函数的原型对象。不是看constructor哦