关于《JavaScript语言精粹》中的原型继承问题
本帖最后由 mccissb 于 2013-03-15 21:19:16 编辑 道格拉斯的《JavaScript语言精粹》中定义了一个Object.beget方法(修订版中为Object.create方法),代码如下:
if (typeof Object.beget!== 'function') {
Object.beget= function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
}
javascript
if (typeof Object.beget!== 'function') {
Object.beget= function(o) {
var newObject = {};
newObject .prototype = o;
return newObject ;
};
}
//两种函数
Object.cr= function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
Object.bt= function(o) {
var newObject = {};
newObject .prototype = o;
return newObject ;
};
//创建原始对象
var o = { x:"o_x", y:"o_y" };
//通过三种不同方法创建新对象
var o_de = o;
var o_cr = Object.cr(o);
var o_bt = Object.bt(o);
//改写原始对象属性
o.x = "o.x2";
o_bt.x= "o_bt";
o_cr.x= "o_cr";
//显示对象的属性和方法
console.dir(o_de);
console.dir(o_cr);
console.dir(o_bt);