首页 > 代码库 > 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构造函数继承
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。