javascript構造函數繼承
阿新 • • 發佈:2017-06-14
函數繼承 scrip color code script this 技術 創建 sna
一.傳統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構造函數繼承