Javascript范围和变量

5 javascript variables scope

var name = "Bob";

var book = {
    name: "Harry Potter",
    writeName: function() {
        return function() {
            document.writeln(this.book.name);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

当我打电话给你

book.writeName()();
Run Code Online (Sandbox Code Playgroud)

我想要它打印哈利波特(而不是鲍勃)它上面做的,但是这个:

var book2 = book;
book = null;
book2.writeName()();
Run Code Online (Sandbox Code Playgroud)

现在寻找this.book(它null)应该寻找的地方this.book2

我该如何引用变量?

Ber*_*rgi 5

你需要的是writeName闭包中的一个变量:

var book = {
    name: "Harry Potter",
    writeName: function() {
        var name = this.name; // turn dynamic property into closure variable
        return function() {
            document.writeln(name);
        }
    }
};
book.writeName()(); // Harry Potter
Run Code Online (Sandbox Code Playgroud)

name您也可以像@ Quentin的答案一样存储对象的引用,而不是只存储在闭包中.如果您计划.name在调用返回的函数之前更改属性,则可能会有所不同.

对于是否使用thisbook引用对象的问题,请参阅自己键的函数中的Javascript:Object Literal引用,而不是'this'.