我試圖將this.SOME_MEMBER傳遞給方法,但它不會像同一個成員一樣通過。下面的代碼應該對我想要了解的東西更有意義。將對象成員(如this.member)傳遞給javascript中的類方法
function App()
{
this.canvas = new Object();
}
App.prototype.createCanvas = function(obj, width, height)
{
obj = document.createElement('canvas');
obj.setAttribute('width', width);
obj.setAttribute('height', height);
log(obj == this.canvas); //false
log(this.canvas == app.canvas); //true
//it's clear that this refers to app
//so why doesn't obj refers to this.canvas?
//how do i get obj to equal this.canvas?
}
App.prototype.init = function()
{
this.createCanvas(this.canvas, 800, 600);
log(this.canvas.width); //undefined
}
var app = new App();
app.init();
現在,我知道我可以只是簡單地做到以下幾點:
function App()
{
this.canvas = new Object();
}
App.prototype.createCanvas = function(width, height)
{
this.canvas = document.createElement('canvas');
this.canvas.setAttribute('width', width);
this.canvas.setAttribute('height', height);
}
App.prototype.init = function()
{
this.createCanvas(800, 600);
log(this.canvas.width); //800
}
var app = new App();
app.init();
這將適用於大多數應用程序,但我只限於命名變量this.canvas。我最終需要這種方法更靈活一些。
請記住,我使用函數document.createElement和element.setAttribute作爲一個例子;他們可以被替換爲修改變量obj的任何東西。
因此,當「this.canvas」被用作參數時,它會發生什麼?我將如何實現我期待的目標?
在此先感謝!
我已經更新了我的答案,很抱歉第一次誤解了這個問題。 –