javascript建構函式繼承

來源:互聯網
上載者:User

標籤:利用   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(){}; //Null 物件幾乎不佔用記憶體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); //Chinesep1.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(){}; //Null 物件幾乎不佔用記憶體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); //Chinesep1.sayName(); //Oliconsole.log(p1.hhh);//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!console.log(p1.hello);//新增!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 

推薦連結:1190000004906911

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

javascript建構函式繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.