您的位置:首页 > Web前端 > JavaScript

js继承

2016-01-20 17:16 691 查看
var o = {
a: 2,
m: function(){
return this.a + 1;
}
};

console.log(o.m()); // 3
// 当调用 o.m 时,'this'指向了o.

var p = Object.create(o);
// p是一个对象, p.[[Prototype]]是o.

p.a = 12; // 创建 p 的自身属性a.
console.log(p.m()); // 13
// 调用 
p.m
时, 'this'指向 p.
// 又因为 p 继承 o 的 m 函数
// 此时的[code]'this.a'
即 p.a,即 p 的自身属性 'a'[/code]
function A(a){
this.varA = a;
}

// 以上函数 A 的定义中,既然 A.prototype.varA 总是会被 this.varA 遮蔽,
// 那么将 varA 加入到原型(prototype)中的目的是什么?
A.prototype = {
varA : null,  // 既然它没有任何作用,干嘛不将 varA 从原型(prototype)去掉?
//
也许作为一种在隐藏类中优化分配空间的考虑?
// https://developers.google.com/speed/articles/optimizing-javascript#Initializing instance variables
// 将会验证如果 varA 在每个实例不被特别初始化会是什么情况。
doSomething : function(){
// ...
}
}

function B(a, b){
A.call(this, a);
this.varB = b;
}
B.prototype = Object.create(A.prototype, {
varB : {
value: null,
enumerable: true,
configurable: true,
writable: true
},
doSomething : {
value: function(){ // override
A.prototype.doSomething.apply(this, arguments); // call super
// ...
},
enumerable: true,
configurable: true,
writable: true
}
});
B.prototype.constructor = B;

var b = new B();
b.doSomething();
最重要的部分是:类型被定义在 
.prototype 中

而你用 
Object.create()
 来继承
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: