Class属性Extends和Implements的区别示例介绍
前端  /  管理员 发布于 6年前   215
代码如下:
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.
代码如下:
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'.
通过Extends实现继承时,需要通过调用parent方法来调用父元素的initialize方法从而继承父元素的属性
而通过Implements实现继承时,直接就可以继承父元素的属性,这种方式很适合父类不止一个的情况下
另外额外补充类方法Implement和extend,这两个方法用于扩展已经定义了的类
代码如下:
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'
“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. */
123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号