このメソッドは作者が独自に作成したものではありません。先人の意見をもとにまとめて、シンプルで実用的な JavaScript の継承メソッドを考え出しただけです。
従来の JavaScript の継承はプロトタイプのプロトタイプ チェーンに基づいており、多数の新しい操作を使用する必要があります。コードは十分に簡潔ではなく、可読性もあまり高くなく、プロトタイプ チェーン汚染の影響を受けやすいようです。 。
著者がまとめた継承方法は簡潔かつ明快ですが、最良の方法ではありませんが、読者のインスピレーションになれば幸いです。
さて、これ以上ナンセンスではありません。コードを見てください。コメントが詳細に記載されているので、一目で理解できます~~~
/**
* Created by Yang Yuan on 14-11-11.
* Implement inheritance without using prototype
*
*/
/**
* Javascript object copy, only one layer is copied, and only the function attribute is copied, which is not universal!
* @param obj The object to be copied
* @returns Object
*/
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;
};
/**
* Traverse all its own attributes of obj
*
* @param callback callback function. The callback will contain two parameters: key attribute name, value attribute value
*/
Object.prototype.each = function(callback){
var key = "",
_this = this;
for (key in _this){
if(Object.prototype.hasOwnProperty.call(_this, key)){
callback(key, _this[key]);
}
}
};
/**
* Create subclass
* @param ext obj, contains methods that need to be rewritten or extended.
* @returns Object
*/
Object.prototype.extend = function(ext){
var child = this.clone();
ext.each(function(key, value){
child[key] = value;
});
return child;
};
/**
* Create object (instance)
* @param arguments accepts any number of parameters as the constructor parameter list
* @returns Object
*/
Object.prototype.create = function(){
var obj = this.clone();
if(obj.construct){
obj.construct.apply(obj, arguments);
}
return obj;
};
/**
* Useage Example
* Use this method of inheritance to avoid the cumbersome prototype and new.
* But the current example written by the author can only inherit the function of the parent class (which can be understood as a member method).
* If you want to inherit richer content, please improve the clone method.
*
*
*/
/**
* Animal (parent class)
* @type {{construct: construct, eat: eat}}
*/
var Animal = {
construct: function(name){
this.name = name;
},
eat: function(){
console.log("My name is " this.name ". I can eat!");
}
};
/**
* Bird (subcategory)
* Birds overrides the eat method of the parent class and extends the fly method
* @type {subclass|void}
*/
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!");
}
});
/**
* Create bird instance
* @type {Jim}
*/
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!