Class特性Extends和Implements的差别示例详细介绍

2021-01-20 10:27 jianzhan

拷贝编码
编码以下:

<span style="font-size:12px;">var Animal = new Class({
initialize: function(age){
this.age = age;
}
});
var Cat = new Class({
Extends: Animal,
initialize: function(name, age){
this.parent(age); // calls initalize method of Animal class
this.name = name;
}
});
var myCat = new Cat('Micia', 20);
console.log(myCat.name); //'Micia'.
console.log(myCat.age); // 20.</span>


拷贝编码
编码以下:

<span style="font-size:12px;">var Dog = new Class({
Implements: Animal,
setName: function(name){
this.name = name
}
});
var myAnimal = new Dog(20);
console.log(myAnimal.age);
myAnimal.setName('Micia');
console.log(myAnimal.name); // 'Micia'.
</span>

根据Extends完成承继时,必须根据启用parent方式来启用父元素的initialize方式从而承继父元素的特性

而根据Implements完成承继时,立即便可以承继父元素的特性,这类方法很合适父类不止1个的状况下

此外附加填补类方式Implement和extend,这两个方式用于拓展早已界定了的类

拷贝编码
编码以下:

<span class="kw2"><span style="font-size:12px"></span></span><pre name="code" class="javascript"><span style="font-size:12px;">var Animal = new Class({
initialize: function(age){
this.age = age;
}
});
Animal.implement({
setName: function(name){
this.name = name;
}
});
var myAnimal = new Animal(20);
myAnimal.setName('Micia');
console.log(myAnimal.name); //'Micia'</span></pre><span style="font-size:12px">
<span class="co1"></span></span>

“The main difference between extend and implement is that Implement changes the class's prototype, while Extend creates a copy. This means that if you implement a change into a class all instances of that class will inherit that change instantly, while if you use Extend then all existing instances will remain the same。”

简易汉语翻译下:extend和implement的关键差别是,implement更改了类的prototype特性,而extend只是新建了1个副本。这代表着假如你根据implement对类做了更改,那将更改他的全部案例,而根据extend更改类的话,不容易更改在此以前存在的案例。

拷贝编码
编码以下:

var Thingy = new Class({
go: function(){
alert('hi');
}
});
var myClass = new Thingy();
myClass.go(); /* alerts 'hi' */
Thingy.implement({
go: function(){
alert('implemented');
}
});
myClass.go(); /* alerts 'implemented' */
Thingy = Thingy.extend({
go: function(){
alert('extended');
}
});
myClass.go(); /* alerts 'implemented'
because extend only affects
new instances. */