当我运行此代码时:
var Test = function() {
return this.stuff;
};
Test.stuff = 'Neat!';
document.write(Test() || 'Not neat.');
Run Code Online (Sandbox Code Playgroud)
为什么我会'不整洁'?为什么我不能使用stuff属性this.stuff?
类方法和变量放在prototype属性上:
Test.prototype.stuff = 'Neat!'
Run Code Online (Sandbox Code Playgroud)
构造函数(我假设这是你想要的,给定大写情况和this)应该与new运算符一起调用:
new Test()
Run Code Online (Sandbox Code Playgroud)
并且它们不应该返回值(您应该使用返回的默认值this)
function Test(){
this.instanceVariable = 17;
//no return!
}
Run Code Online (Sandbox Code Playgroud)
至于您的真正需求,您可以直接访问该功能及其属性
function Test(){
return Test.stuff;
}
Run Code Online (Sandbox Code Playgroud)
但是,我并不是滥用像这样的命名空间函数的忠实粉丝.我更喜欢有一个命名空间对象来做事
//in a real case I would probably use the module pattern for private variables
//but whatever...
var Namespace = {};
Namespace.stuff = 'Neat!';
Namespace.F = function(){
console.log(Namespace.stuff);
};
Run Code Online (Sandbox Code Playgroud)
这就是你所做的:
var Test = function() { //Test is a Function object
return this.stuff; //this is a pointer to an object, not Test
};
Test.stuff = 'Neat!'; //Add a property to Test
document.write(Test() || 'Not neat.'); //this has no property stuff
Run Code Online (Sandbox Code Playgroud)
将代码的最后一行更改为:
document.write(Test.call(Test) || 'Not neat.'); //this now points to Test
Run Code Online (Sandbox Code Playgroud)
你的代码不起作用的原因是因为this指针指向:
new关键字为前缀时创建的构造函数的实例.(例如var foo = new Foo(); //the this in Foo points to foo [for the sake of explanation]).call和apply作为第一个参数的对象.你想要做的事情是这样的:
var Test = function Temp() { //Test is a Function object, alias Temp
return Temp.stuff; //Temp is the same as Test, only locally
};
Test.stuff = 'Neat!'; //Add a property to Test
document.write(Test() || 'Not neat.'); //writes Neat!
Run Code Online (Sandbox Code Playgroud)
如果你喜欢它,请回答这个问题.干杯.