寫這個話題單純是給本身作筆記了,否則老忘記。app
第一種方法:
ide
function fn1(x) { this.x = x; } function fn2(x, y) { this.tmpObj = fn1; this.tmpObj(x); delete this.tmpObj; this.y = y; }
第二種方法:call()或apply()this
function fn1(x) { this.x = x; } function fn2(x, y) { fn1.call(this, x); this.y = y; }
第三種方法:原型鏈繼承
spa
function fn1(x) { this.x = x; } fn1.prototype.y = function() { console.log("i am pomelo"); } function fn2() {} fn2.prototype = new fn1(); fn2.prototype.constructor = fn2; var fn2Obj = new fn2(); fn2Obj.y();
實際用得最多的是第二種和第三種。prototype
function fn1(x) { this.x = x; } fn1.prototype.z = function() { console.log("i am pomelo"); } function fn2(x, y) { fn1.apply(this, [x]); this.y = y; } fn2.prototype = new fn1(); fn2.prototype.constructor = fn2; var fn2Obj = new fn2(1024, 2048); console.log(fn2Obj.x); console.log(fn2Obj.y); fn2Obj.z();