标签:creat 比较 person name val prot 函数 nts 对象
// 继承方式1 ==> 默认的原型继承
function Person() {}
Person.prototype.run = function() {};
var xiaohong = new Person();
// 继承方式2 ==> 置换后的原型继承
function Person() {}
Person.prototype = {
say: function() {}
}
var xiaohong = new Person();
// 继承方式3 ==> 寄生式继承
var obj = { val: 100 };
var newObj = Object.create( obj );
// 继承方式4 ==> 混入继承
function extend( o1, o2 ) {
for( var key in o2 ) {
o1[key] = o2[key];
}
}
var o = { abc: 888 };
var o2 = { aaa: 111, bbb: 222, ccc: 333 };
extend( o, o2 );
// 继承方式5 ==> 对象冒充( 构造函数借用 )
function Person( name, age, sex ) {
this.name = name;
this.age = age;
this.sex = sex;
}
function Student( name, age, sex ) {
this.Person = Person;
this.Person( name, age, sex );
delete this.Person;
}
function Student( name, age, sex ) {
//Person.call( this, name, age, sex );
Person.apply( this, arguments );
}
var xiaohong = new Student(‘小红‘, 16);
console.log( xiaohong );
// 继承方式6 ==> 原型组合继承
function Person( name, age, sex ) {
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype = {
run: function() {
console.log(‘人都会跑‘);
}
};
function Student( name, age, sex ) {
Person.apply( this, arguments );
}
// 解决方案1:
// 这样可以,但是不建议,因为一定会给Student添加一些额外的方法,
// 这些方法不应该和Person共享
//Student.prototype = Person.prototype;
// 解决方案2,混入继承,可取,用的也比较多
//extend( Student.prototype, Person.prototype );
// 解决方案3,原型寄生组合式继承
//Student.prototype = Object.create( Person.prototype );
// 解决方案4,
Student.prototype = new Person;
// xiaofang ==> Student.prototype ==> Person.prototype ==> Object.prototype ==> null
var xiaofang = new Student( ‘小芳‘, 17, ‘女‘ );
xiaofang.run();
/*
* 理想的继承解决方案:
* */
function Person( name, age, sex ) {
this.name = name;
this.age = age;
this.sex = sex;
}
Person.prototype = {
run: function() {
console.log(‘人都会跑‘);
}
};
function Student( name, age, sex ) {
Person.apply( this, arguments );
}
// 让学生实例,继承Student.prototype & Person.prototype
Student.prototype = Object.create( Person.prototype );
// 再给Student扩展自己独有的方法
extend( Student.prototype, {
} );
标签:creat 比较 person name val prot 函数 nts 对象
原文地址:http://www.cnblogs.com/luxiaoxiao/p/6102977.html