"这个"指的是别的什么?

Ali*_*anC 2 javascript

当我运行此代码时:

var Test = function() {
    return this.stuff;
};

Test.stuff = 'Neat!';

document.write(Test() || 'Not neat.');
Run Code Online (Sandbox Code Playgroud)

为什么我会'不整洁'?为什么我不能使用stuff属性this.stuff

hug*_*omg 5

类方法和变量放在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)

  • @AlicanC是John Resig关于该主题的帖子.http://ejohn.org/blog/simple-class-instantiation/ (2认同)
  • @AlicanC - 根据我的理解,你真正想要的是一个类似于我在答案中描述的模式(即`var Test = function Temp(){return Temp.stuff;};`).它很快,而且很优雅.另外,即使人们稍后改变了像`Test = 5;`这样的代码,它也不会破坏你的代码作为函数的内部名称(即`Temp`),仍然指向函数本身.它无法从外部修改.希望这可以帮助.干杯. (2认同)

Aad*_*hah 5

这就是你所做的:

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指针指向:

  1. 当函数调用以new关键字为前缀时创建的构造函数的实例.(例如var foo = new Foo(); //the this in Foo points to foo [for the sake of explanation]).
  2. 传递给的对象callapply作为第一个参数的对象.

你想要做的事情是这样的:

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)

如果你喜欢它,请回答这个问题.干杯.