標籤:
1. js 其實是一個非物件導向的語言,通過對象的深淺複製完成繼承
2. 繼承方法
繼承的方法有兩種
1)prototype 原型模式
舉個例子
var Animal = function () { this.type = ‘animal‘; this.tmp = {name:‘hehe‘}; this.eat = function (tmp) { console.log(‘animal eat‘); }; this.modifyTmp = function (tmp) { this.tmp.name = tmp; }}var Cat = function (name) { this.type = ‘cat‘; this.name = name; this.eat = function () { console.log(‘cat eat:‘ + this.name); }}Cat.prototype = new Animal();var cat1 = new Cat(‘cat1‘);cat1.eat();cat1.modifyTmp(‘lala‘);console.log(cat1.tmp); // 輸出 lalavar cat2 = new Cat(‘cat2‘);cat2.eat();console.log(cat2.tmp); // 輸出lalaView Code
注意:此處有坑!!
為什麼通過原型繼承輸出的都是 lala 呢?
因為此時的 tmp 的類型為對象 或者 array, 當進行 prototype 繼承時, 實際是通過對象引用完成繼承,此時 cat1 cat2 都是指向同一個Animal 對象。如果tmp 為基礎類型(string,int)時,不存在引用,可以無需擔心。
可以將 tmp 重新定義給外部 cat1 cat2 對象,進行重新複製,將會指向兩個不同對象,例子如下:
var Animal = function () { this.type = ‘animal‘; this.tmp = {name:‘hehe‘}; this.eat = function (tmp) { console.log(‘animal eat‘); }; this.modifyTmp = function (tmp) { this.tmp.name = tmp; return this.tmp; }}var Cat = function (name) { this.type = ‘cat‘; this.name = name; this.tmp = {}; this.eat = function () { console.log(‘cat eat:‘ + this.name); this.tmp = this.tmp; }}Cat.prototype = new Animal();var cat1 = new Cat(‘cat1‘);cat1.eat();cat1.tmp = cat1.modifyTmp(‘lala‘);console.log(‘cat1‘,cat1); // lalavar cat2 = new Cat(‘cat2‘);cat2.eat();cat2.tmp = cat2.modifyTmp(‘miaomiao‘);console.log(‘cat2:‘,cat2); // miaomiaoconsole.log(‘cat1‘,cat1); // lalaView Code
2) call apply 方式
這個是利用this 對象偷天換日。
【javascript】繼承