/*
代码复用
*/
/*
一、避免
*/
/*
模式1:默认模式
*/
function Parent() {
this.name = "123";
}
Parent.prototype.say = function () {
return this.name;
}
function Child(name) { }
Child.prototype = new parent();
var kid = new Child();
kid.name = "abc";
kid.say(); //abc
// 缺点:不能让参数传进给Child构造函数
var s = new Child('Seth');
console.log(s.say()); // "123"
/*
二、推荐
*/
// 1. 模式1:原型继承
function object(o) {
function F() {
}
F.prototype = o;
return new F();
}
// 要继承的父对象
var parent = {
name: "Papa",
};
// 新对象
var child = object(parent);
// 父构造函数
function Person() {
// an "own" property
this.name = "Adam";
}
// 给原型添加新属性
Person.prototype.getName = function () {
return this.name;
};
// 创建新person
var papa = new Person();
// 继承
var kid = object(papa);
console.log(kid.getName()); // "Adam"
// 继承原型
var kid = object(Person.prototype);
console.log(typeof kid.getName); // "function",因为是在原型里定义的
console.log(typeof kid.name); // "undefined", 因为只继承了原型
//使用ECMAScript5
/* 使用新版的ECMAScript 5提供的功能 */
var child = Object.create(parent);
var child = Object.create(parent,
{
age: { value: 2 }
// ECMA5 descriptor
});
console.log(child.hasOwnProperty("age")); // true
// 2. 模式2:复制所有属性进行继承
// 3. 模式3:混合(mix-in)
// 4. 模式4:借用方法