首先让我们回顾一下 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
我希望现在一切看起来都很容易。