
正文
JavaScript中的继承
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、原型链(默认)
function Person(){};
function Student(){};
Student.prototype = new Person();
Student.prototype.constructor = Student;
缺点:1、传参怎么搞 ? 2、new Person的实例属性成了Student的原型属性
二、借用构造函数
function Person(name) { this.name = name;}
function Student(name, klass) { Person.call(this, name); this.klass = klass;}
优点:传参搞定了哦 缺点:方法继承呢 继承 呢
三、组合继承(原型链+借用构造函数)
function Person(name){
this.name = name;
}
function Student(name, klass){
Person.call(this, name);
this.klass = klass;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
还存在缺点:1、new Person的实例属性成了Student的原型属性 2 Person构造函数被调用了两次,效率低下
四、临时构造函数
function Person(name){
this.name = name;
}
function Student(name, klass){
Person.call(this, name);
this.klass = klass;
}
(function(){
var F = function(){};
F.prototype = Person.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
})();
看起来不错哦~~
但素,JavaScript为啥非得类式继承捏
重点来了,
原型继承
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
原型链,链起来:new student() -----> Student.prototype----->Person.prototype-----> Object.Prototype
把你的心,我的心,串一串,串一株幸运草,串一个同心圆~~
Object.create polyfill
if(typeof Object.create !== 'function'){
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
}
}
额外的,通过复制属性实现继承
function extendDeep(parent, child){
var i;
child = child || {};
for(i in parent){
if(parent.hasOwnProperty(i)){
if(typeof parent[i] === 'object'){
child[i] = (Object.prototype.toString.call(parent[i]) === '[object Array]') ? [] : {};
extendDeep(parent[i], child[i]);
}else{
child[i] = parent[i];
}
}
}
return child;
}







