温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Class中Extends和Implements属性的区别是什么

发布时间:2021-06-25 15:44:41 来源:亿速云 阅读:400 作者:Leah 栏目:web开发

这篇文章给大家介绍Class中Extends和Implements属性的区别是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。


<span >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 >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实现继承时,直接就可以继承父元素的属性,这种方式很适合父类不止一个的情况下

另外额外补充类方法Implement和extend,这两个方法用于扩展已经定义了的类

代码如下:


<span class="kw2"><span ></span></span><pre name="code" class="javascript"><span >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 >
<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只是新建了一个副本。这意味着如果你通过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. */

关于Class中Extends和Implements属性的区别是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI