javaScript属性和方法同在构造函数中(包含继承)
将所有属性和方法使用this声明,并放在构造函数中,不使用prototype.
例子:
function Animal(name) {
this.name = name;
this.run = function() {
alert("running "+this.name)
};
}
var animal = new Animal('Foxie');
animal.run();
此类型的继承:
1、使用apply或call调用父类构造函数获得父类的属性和方法
2、在子类中添加新的属性和方法
栗子:
function Rabbit(name) {
Animal.apply(this, arguments); // inherit
this.bounce = function() {
alert("bouncing "+this.name);
}
}
rabbit = new Rabbit("Rab");
rabbit.bounce(); // own method
rabbit.run(); // inherited method
此种继承没有使用prototype意味着子类和父类的方法均独立在自己的对象中,没有共用的属性或方法。也就是没有达到方法的复用,子类和父类可能有着功能完全相同的方法。但是在这种模式中也有自己的有点,它支持private属性。
使用var在构造函数里边声明定义的属性和方法就是private类型,他的访问速度是非常快的。在构造函数的外部无法访问。
protected类型的属性同样使用命名规范’_‘约束,并不是强制性的。
子类中的重写只需使用this.methidName即可。重写之前可将父类方法寄存,以便后续调用。
因为没有使用prototype所以rabbit instanceof Animal 在这里是不奏效的。
还没有评论,来说两句吧...