4

我不明白以下内容:

var x = function() {
    this.foo="foo";
    return function() {
        this.bar = "bar";
        return foo+bar;
    };
}(); // returns inner

alert(x()); // 'foobar', so both 'this' variables are set
alert(x.bar); // undefined - but wasn't it used correctly?
alert(new x().bar); // ok, works

我的假设是第一次生成并使用默认的“this”范围/变量映射,然后在调用“new”时,发送并返回一个带有新“this”的新对象(函数?)。或者,也许 x 不是一个合适的对象?但是,“this”最终是如何被设置并用于制作“foobar”的呢?

我需要知道什么才能理解这一点?

4

4 回答 4

9

首先让我们回顾一下 JavaScript 的一些要点,然后我们可以处理您的示例。

函数的上下文

误解之一是上下文。每个函数都在上下文中调用,可以使用关键字来调用this。让我们编写一个可以用来检查上下文的函数:

var probe = function(){
  // if the context doesn't have a name, let's name it
  if(!this.name){
    this.name = "lumberjack";
  }
  // print the name of my context
  console.log(this.name);
};

开始了:

name = "global!";

// when we call a function normally it still have a context:
// the global context
probe(); // prints: global!

var ctx = {name: "ctx"};

// we can set a context explicitly using call()
probe.call(ctx); // prints: ctx

// we can set a context explicitly using apply()
probe.apply(ctx); // prints: ctx

// it is set implicitly, if we call a function as a member
ctx.fun = probe;
ctx.fun(); // prints: ctx

// or we can create a brand new object and set it as a context:
// that's what "new" does
var t = new probe(); // prints: lumberjack

// let's sum it up:
console.log(name);     // prints: global!
console.log(ctx.name); // prints: ctx
console.log(t.name);   // prints: lumberjack

这就是为什么很容易搞砸并在不经意间陷入全球环境的原因。

在构造函数中返回值

许多人在看到构造函数返回值时会感到困惑。这是合法的。构造函数可以返回一个对象、一个函数或一个数组。该值将用作实例。旧实例将被丢弃。

var myClass = function(){
  // if it is called as a constructor, "this" will be a new instance
  // let's fill it up:
  this.a = 42;
  this.b = "Ford";
  this.c = function(){ return "Perfect"; };
  // done? let's discard it completely!
  // and now for something completely different...
  return {
    owner: "Monty Python",
    establishment: "Flying Circus"
  };
};
var t = new myClass();
alert(t.owner + "'s " + t.establishment);

正如预期的那样,它显示了“Monty Python's Flying Circus”。

如果构造函数返回其他内容(例如,数字、字符串、null、未定义),则返回的结果将被丢弃并使用旧实例。

这个例子

您的示例很难理解,主要是因为它的编写方式。让我们通过重写来简化它。

首先让我们处理x

var x = function() {
  this.foo = "foo";
  return function() {
    this.bar = "bar";
    return foo + bar;
  };
}(); // returns inner

我们可以看到匿名函数(第一个 function立即执行,所以我们可以内联它:

// next assignment can be simplified because
// top "this" is window or the global scope
//this.foo = "foo"; =>
foo = "foo";
x = function() {
  this.bar = "bar"; // this line depends on its context, or "this"
  return foo + bar; // this line uses global "foo" and "bar"
};

所以最后我们有两个全局变量:(foo一个字符串)和x(一个函数)。

现在让我们回顾一下第一个警报

alert(x()); // 'foobar', so both 'this' variables are set

再次,让我们内联x()

// next assignment can be simplified because
// top "this" is window or the global scope
//this.bar = "bar"; =>
bar = "bar";
// at this moment both global "foo" and "bar" are set
alert(foo + bar); // => "foo" + "bar" => "foobar"

第二个警报同样简单:

alert(x.bar); // undefined - but wasn't it used correctly?

它不需要太多的重写。x是一个函数,我们没有给它添加任何属性,所以x.bar是未定义的。如果添加它,您可以看到结果:

x.bar = "bar2";
alert(x.bar); // bar2

第 3 个警报演示了 JavaScript 的 OOP 实际操作:

alert(new x().bar); // ok, works

(附带说明:它仅因为您x()先运行而起作用,否则它会因为bar未定义而爆炸)。

让我们像这样重写它:

var t = new x();
alert(t.bar); // bar

现在让我们分析构造函数。它有两个语句:赋值和返回。后者被忽略,因为它返回一个字符串。所以我们可以这样重写它:

x = function(){
  this.bar = "bar";
};
var t = new x();
alert(t.bar); // bar

我希望现在一切看起来都很容易。

于 2009-08-16T09:16:55.710 回答
4

这是运营商的主要抱怨......

该运算符创建一个继承自操作数构造函数原型的新对象,然后调用该函数,将新对象分配给this.

如果在调用构造函数时忘记使用 new 运算符,您将获得正常的函数调用,并且this绑定到全局对象 ( window) 而不是新对象。

您的函数将在this尝试初始化自己的实例时附加全局变量。

在您的示例中,全局对象以两个新变量结束:

window.foo
window.bar

因此,有些人更喜欢原型继承而不是伪经典方法。

于 2009-08-16T07:18:34.370 回答
3
于 2009-08-16T07:02:31.913 回答
3

正如 Shog9 所说,这与您在 Java 等中看到的正常范围不同。

AFAIK Javascript 使用动态范围,就像 Common LISP/eLisp 一样,而不是像 Scheme/Lisp-1 那样的词法范围。

于 2009-08-16T07:08:46.890 回答