5)Javascript设计模式:extends模式

时间:2022-09-17 05:20:48

简单的方式


function Person() {
this.name = 'person';
}
Person.prototype.say = function() {}; function Child() {
this.name = 'child';
}
Child.prototype = new Person(); var child = new Child();

缺点:其实child并不需要person里面的name属性

借用构造函数


function Person() {
this.name = 'person';
}
Person.prototype.say = function() {}; function Child() {
Person.call(this, arguments)
} var child = new Child();

缺点:仅会复制父类对象的属性作为子类自身的属性, 仅仅是复制**

优点:可以获得父对象自身的真实副本,子类和父类没有关系,不会影响到父类**

借用构造函数是实现多继承

function CatWings() {
Cat.call(this, arguments)
Brid.call(this, arguments)
}

借用构造函数和实现原型


function Person() {
this.name = 'person';
}
Person.prototype.say = function() {}; function Child() {
Person.call(this, arguments)
// this.name = 'child'
} Child.prototype = new Person() var child = new Child();
delete child.name;
// 可以看到访问:child.name的是prototype的

name属性被继承了2次

缺点:所有从Person继承的类,都是可以更改到Person的原型方法

临时构造函数

function inherit(Child, Parent) {
var F = function(){}
F.prototype = Parent.prototype;
Child.prototype = new F();
// Child.prototype.constructor = Child
// Child.superclass = Parent.prototype;
} // 每次都要创建一个空的F
var inherit = (function(){
var F = Function(){};
return function() {
F.prototype = Parent.prototype;
Child.prototype = new F();
// Child.prototype.constructor = Child
// Child.superclass = Parent.prototype;
}
})();

Klass

var Klass = function (Parent, props) {

    if(props == undefined && typeof Parent == 'object') {
props = Parent;
Parent = null;
} Parent = Parent || {};
props = props || {}; var Child = function() {
if(Child.superclass.hasOwnProperty('__construct')) {
Child.superclass['__construct'].apply(this, arguments);
} if(Child.prototype.hasOwnProperty('__construct')) {
Child.prototype['__construct'].apply(this, arguments);
}
}; var F = function() {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype; for(var i in props) {
if(props.hasOwnProperty(i)) {
Child.prototype[i] = props[i];
}
}
return Child;
} function Animal() {} Animal.prototype.__construct = function(name) {
this.name = name
}; Animal.prototype.getName = function() {
return this.name;
}; var Dog = Klass(Animal, {
__construct: function(name, age) {
this.age = age;
},
run: function() {
console.log('My name is %s, I\'m %s years old , I\'m Running', this.getName(), this.age);
}
}); var dog = new Dog('xixi', 26)