當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript构造函数继承
生活随笔
收集整理的這篇文章主要介紹了
javascript构造函数继承
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一.傳統(tǒng)prototy繼承
function Parent() {this.name = "thisIsName"; } Parent.prototype.sayName = function() {return this.name; };function Child() {this.age = "thisIsAge"; }Child.prototype = new Parent();/指向Parent實(shí)例(包括實(shí)例的屬性和原型) 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());?
二.利用對(duì)象空間繼承
創(chuàng)建一個(gè)新的構(gòu)造函數(shù)F,為空對(duì)象,幾乎不占內(nèi)存
function Chinese() {} Chinese.prototype.nationality = "Chinese";function Person(name, age) {this.name = name;this.age = age; }
function F(){}; //空對(duì)象幾乎不占用內(nèi)存 F.prototype = Chinese.prototype; //指向同一個(gè)原型,互相影響 Person.prototype = new F();//new后地址指向F.prototype,F.proptotype也是一個(gè)指向原型的地址,故操作Person.prototype不會(huì)影響到父類的原型 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(){}; //空對(duì)象幾乎不占用內(nèi)存 F.prototype = Chinese.prototype; //指向同一個(gè)原型,互相影響 Person.prototype = new F();//new后地址指向F.prototype,F.proptotype也是一個(gè)指向原型的地址,故操作Person.prototype不會(huì)影響到父類的原型 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
轉(zhuǎn)載于:https://www.cnblogs.com/krystalcl/p/7008148.html
總結(jié)
以上是生活随笔為你收集整理的javascript构造函数继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编程语言注释方法大全
- 下一篇: Angular服务http post传递