javascript原型继承实现_javascript Prototypal inheritance

javascript设计模式中原型继承有说明设置一个对象属性和读取一个对象属性存在差异的问题,本质上其实应该归结到原型编程的特性上,因为javascript使用原型链来实现对象继承特性,但是原型编程中有一个很重要的概念:原型槽,访问一个属性,先访问对象本身的名为这个属性名的属性,若属性不存在,则访问原型中同名的属性。而修改对象本身的一个属性却不会影响到原型对象,所以才会造成这种差异。

书中原型继承实现方式如下:

var CompoundObject = {
string1: ‘default value’,
childObject: {
bool: true,
num: 10
}
}

var compoundObjectClone = clone(CompoundObject);

// Bad! Changes the value of CompoundObject.childObject.num.
compoundObjectClone.childObject.num = 5;

// Better. Creates a new object, but compoundObject must know the structure
// of that object, and the defaults. This makes CompoundObject and
// compoundObjectClone tightly coupled.
compoundObjectClone.childObject = {
bool: true,
num: 5
};

// Best approach. Uses a method to create a new object, with the same structure and
// defaults as the original.

var CompoundObject = {};
CompoundObject.string1 = ‘default value’,
CompoundObject.createChildObject = function() {
return {
bool: true,
num: 10
}
};

//这里讲到对于对象中的子对象,最好使用工厂方式来创建,而不是直接写在父对象里面
CompoundObject.childObject = CompoundObject.createChildObject();

var compoundObjectClone = clone(CompoundObject);
compoundObjectClone.childObject = CompoundObject.createChildObject();

compoundObjectClone.childObject.num = 5;

//克隆方法使用一个空函数,最后获得一个原型为父对象的空函数对象.最后一句表示通过构造器获取对象

function clone(object) {
function F() {}
F.prototype = object;
return new F;
}