为什么“这”不是我期望的?
一直以为我非常了解js闭包,并且太聪明和性感而不会遇到这样的问题,但是我准备成为一名功能强大的无神论者...
观察示例代码js Ninjas:
function Drawing (id, element) {
/*
* Section A: value of 'this' object of type 'Drawing' (expected);
* Variables I ought to have access to from any point in Drawing's invocation
*/
{ // Preconstruction
var Drawing = this;
var SVG = document.createElementNS('http://www.w3.org/2000/svg', "SVG");
support.dom.Associative.call(Drawing, id, element);
element = Drawing.$(); // In case element was null
element.className = "Drawing";
// Things in or about the drawing
var shapes = [];
}
function add (shape) {
/*
* Section B: value of 'this' Window object
* What gives in this function?
* Variables I have access to from section A:
* element: yes, id: no, Drawing: no, SVG: yes
* ?$@#$%^$#!!!!! Help me!
*/
if (shape instanceof Shape) {
shapes.push(shape);
if(!this.render) SVG.appendChild(shape.toSVG());
return shape;
}
}
this.modify = function (options) {
if (options.create) {
return add(create[options.create](options));
}
};
}
我没有得到什么?
function add
是在function Drawing
中定义的,在我的野外应用程序中,没有其他任何命名或定义为add'add'的函数。我期望的功能实际上是在调用,我在其中进行了分解,看到我可以从Drawing的调用中访问某些由闭包定义的var,但似乎并非全部或至少是这种方式。
请教育我,也许我犯了一个愚蠢的错误,另一双眼睛会有所帮助...我准备放弃我所知道的一切错误的科学:)
以下是精神上令人讨厌的输出的上限:
最佳答案
因此,我找出了思路上的错误,并在下面写了一个简单的例子来说明我的困惑:希望这对其他人有帮助!
function Class () {
// this: an object with a prototype of Class, if 'new'ed, window otherwise
var that = this;
function privateMethod () {
// this: a reference to window. privateMethod still belongs to Class' closure
var dat = this;
// that: an object with a prototype of Class, if 'new'ed, window otherwise
var dis = that;
}
}
我用预先定义的
this
替换了对var Drawing = this;
的引用(很多人使用var that = this
形式),尽管内联控制台命令行不提供该引用,但该引用仍然存在。赞赏引发答案的发人深省的思想!
我再次相信。