我正在尝试将 this.SOME_MEMBER 传递给一个方法,但它不会像同一个成员一样通过。下面的代码应该对我想要了解的内容更有意义。
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”被用作参数时,它会发生什么?我将如何实现我想要做的事情?
提前致谢!