码迷,mamicode.com
首页 > 编程语言 > 详细

javascript构造函数继承

时间:2017-06-14 14:27:11      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:利用   oop   定义   class   cto   属性   alt   chinese   包括   

一.传统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构造函数继承

标签:利用   oop   定义   class   cto   属性   alt   chinese   包括   

原文地址:http://www.cnblogs.com/krystalcl/p/7008148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!