此代码直接从以下位置复制:
http://www.bennadel.com/blog/2264-Changing-The-Execution-Context-Of-Your-Self-Executing-Function-Blocks-In-JavaScript.htm
// Set the singleton value to the return value of the self-
// executing function block.
var singleton = (function(){
// Declare a private variable.
var message = "Stop playing with your context!";
this.getMessage = function(){
return( message );
};
// Return this object reference.
return( this );
}).call( {} );
// alert the singleton message.
alert( "Message:", singleton.getMessage());我的想法是,我可以使用它来更好地包含程序中的变量和函数。
但是,当我尝试在JSfiddle中运行代码时:
http://jsfiddle.net/xSKHh/
它不返回消息。我遗漏了什么?
发布于 2012-10-12 11:34:48
警报中缺少加号而不是逗号。试着这样做:
alert( "Message:" + singleton.getMessage());https://stackoverflow.com/questions/12851805
复制相似问题