js原型模式和继承

function SuperType() {
    this.property = true; //原型属性
}
//基类方法
SuperType.prototype.getSuperValue = function() {
    return this.property;
}

function SubType() {
    this.subproperty = false; //子类属性
}
//继承SuperType
SubType.prototype = new SuperType();
//定义子类方法
SubType.prototype.getSubValue = function() {
    return this.subproperty;
}

var instance = new SubType();

console.log(instance.getSuperValue()); //true 基类方法
console.log(instance.getSubValue()); //true 子类方法

//借用构造函数模式
function SuperType() {
    this.colors = ['red', 'blue', 'green'];
}

function SubType() {
    SuperType.call(this); //this 继承SuperType
}

var instance1 = new SubType();
instance1.colors.push("black");
console.log(instance1.colors); //red,blue,green,black

var instance2 = new SubType();
consoles.log(instance2.colors);

  

原文地址:https://www.cnblogs.com/ms_senda/p/11463380.html