首页 > 代码库 > javascript构造函数继承

javascript构造函数继承

一.传统prototy继承

function Parent() {
    this.name = "thisIsName";
}
Parent.prototype.sayName = function() {
    return this.name;
};

function Child() {
    this.age = "thisIsAge";
}

Child.prototype = new Parent();/指向Parent实例(包括实例的属性和原型)
Child.prototype.constructor = Child;

Child.prototype.sayAge = function() {
    return this.age;
};

var c = new Child();
console.log(c.name);
console.log(c.age);
console.log(c.sayName());
console.log(c.sayAge());

 技术分享

二.利用对象空间继承

创建一个新的构造函数F,为空对象,几乎不占内存

function Chinese() {}
Chinese.prototype.nationality = "Chinese";
function Person(name, age) { this.name = name; this.age = age; }
function F(){}; //空对象几乎不占用内存 F.prototype = Chinese.prototype; //指向同一个原型,互相影响 Person.prototype = new F();//new后地址指向F.prototype,F.proptotype也是一个指向原型的地址,故操作Person.prototype不会影响到父类的原型 Person.prototype.constructor = Person; Person.prototype.sayName = function() { //Person的prototype中的方法和属性需要在继承之后定义 console.log(this.name); };
var p1 = new Person("Oli", 18); console.log(p1.nationality); //Chinese p1.sayName(); //Oli

 技术分享

若想继承非原型上的属性可增加Chiness.call(this);

function Chinese() {
    this.hhh = ‘hhh‘;//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    this.hello = ‘hello‘;//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
}
Chinese.prototype.nationality = "Chinese";

function Person(name, age) {
    Chinese.call(this);//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    this.name = name;
    this.age = age;
}

function F(){}; //空对象几乎不占用内存
F.prototype = Chinese.prototype; //指向同一个原型,互相影响
Person.prototype = new F();//new后地址指向F.prototype,F.proptotype也是一个指向原型的地址,故操作Person.prototype不会影响到父类的原型
Person.prototype.constructor = Person;

Person.prototype.sayName = function() { //Person的prototype中的方法和属性需要在继承之后定义
    console.log(this.name);
};

var p1 = new Person("Oli", 18);
console.log(p1.nationality); //Chinese
p1.sayName(); //Oli
console.log(p1.hhh);//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
console.log(p1.hello);//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

技术分享

 

推荐链接:https://segmentfault.com/a/1190000004906911

http://javascript.ruanyifeng.com/oop/pattern.html#toc0

javascript构造函数继承