標籤:利用 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建構函式繼承