我对javascript相当陌生,并试图学习一些最佳实践。 我不清楚为什么我无法访问以下代码中的 ctx 引用。 日志从 myApp.init() 输出一个 context2d 引用。 我可以不在 myApp 模块的返回语句中公开私有对象变量吗? 我以为我开始理解这种语言的基础知识,但对这个看似简单的概念感到沮丧。 感谢您的帮助。
window.onload = function () {
myApp.init();
console.log(myApp.ctx); // logs undefined
};
var myApp = (function () {
var canvas,
ctx,
init = function () {
canvas = document.getElementById("canvas");
ctx = canvas.getContext('2d');
console.log(ctx); // logs valid context2d object
};
return {
init : init,
ctx : ctx
};
}());
myApp.board = (function () {
var ctx = myApp.ctx;
return {
ctx : function () { console.log(ctx); } // logs undefined
};
}());
您需要调用init()
才能定义ctx
。然而,到那时,为时已晚,因为myApp包含ctx的原始值。
您对var ctx = myApp.ctx;
有完全相同的问题.这将在定义 board
时获取 ctx 的值。如果myApp.ctx
发生变化,它不会改变。
这应该有效:
var myApp = new function () {
var canvas;
this.init = function () {
canvas = document.getElementById("canvas");
this.ctx = canvas.getContext('2d');
console.log(this.ctx); // logs valid context2d object
};
};
myApp.board = new function () {
this.ctx = function () { console.log(myApp.ctx); }
};
通过使用 new
关键字,函数成为构造函数(并立即调用) - this
引用正在创建的对象。