JS中继续体式格局的完成有多种要领,下面是比较引荐的要领,别的继续体式格局可做相识:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function inheritPrototype(subType, superType) {
var newObj = object(superType.prototype);
newObj.constructor = subType;
subType.prototype = newObj;
}
function People() {
this.cls = 'people';
}
People.prototype.say = function(name) {
name = name || this.cls;
console.log('My class is '+ name);
}
function Student() {
People.call(this);
this.type = 'student';
}
inheritPrototype(Student, People);
Student.prototype.goToSchool = function() {
console.log('I go to school every day.');
}
// 测试
var stu = new Student();
console.log('class: ' + stu.cls); // class: people
console.log('type: ' + stu.type); // type: student
stu.say(); // My class is people
stu.goToSchool (); // I go to school every day.
实在,javascript 已供应了更简朴的完成要领,没必要在这造轮子,而且要领不完善,MDN 例子:
// Shape - 父类(superclass)
function Shape() {
this.x = 0;
this.y = 0;
}
// 父类的要领
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - 子类(subclass)
function Rectangle() {
Shape.call(this); // call super constructor.
}
// 子类续承父类
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?',
rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'
假如你希望能继续到多个对象,则可以运用混入的体式格局:
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
// 继续一个类
MyClass.prototype = Object.create(SuperClass.prototype);
// 夹杂别的
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// 从新指定constructor
MyClass.prototype.constructor = MyClass;
MyClass.prototype.myMethod = function() {
// do a thing
};