此方法并非笔者原创,笔者只是在前辈的基础上,加以总结,得出一种简洁实用的Javascript继承方法。
传统的Javascript继承基于prototype原型链,并且需要使用大量的new操作,代码不够简洁,可读性也不是很强,貌似还容易受到原型链污染。
笔者总结的继承方式,简洁明了,虽然不是最好的方式,但希望能给读者带来启发。
好了,废话不多说,直接看代码,注释详尽,一看就懂~~~
复制代码 代码如下:
Object.prototype.clone = function(){
var _s = this,
newObj = {};
_s.each(function(key, value){
if(Object.prototype.toString.call(value) === "[object Function]"){
newObj[key] = value;
}
});
return newObj;
};
Object.prototype.each = function(callback){
var key = "",
_this = this;
for (key in _this){
if(Object.prototype.hasOwnProperty.call(_this, key)){
callback(key, _this[key]);
}
}
};
Object.prototype.extend = function(ext){
var child = this.clone();
ext.each(function(key, value){
child[key] = value;
});
return child;
};
Object.prototype.create = function(){
var obj = this.clone();
if(obj.construct){
obj.construct.apply(obj, arguments);
}
return obj;
};
var Animal = {
construct: function(name){
this.name = name;
},
eat: function(){
console.log("My name is "+this.name+". I can eat!");
}
};
var Bird = Animal.extend({
eat: function(food){
console.log("My name is "+this.name+". I can eat "+food+"!");
},
fly: function(){
console.log("I can fly!");
}
});
var birdJim = Bird.create("Jim"),
birdTom = Bird.create("Tom");
birdJim.eat("worm"); //My name is Jim. I can eat worm!
birdJim.fly(); //I can fly!
birdTom.eat("rice"); //My name is Tom. I can eat rice!
birdTom.fly(); //I can fly!



