Class属性Extends和Implements的区别

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. */


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

michael_yqs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值