一直以为我理解js关闭得很好,太聪明和性感,遇到这样的问题,但我已经准备好成为一名功能无神论者......
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& #39;
我期望的函数实际上是在调用,我在其中查看并看到我可以访问来自Drawing调用的闭包定义变量的某些,但不是所有或至少看起来像这样。
请教我,也许我犯了一个愚蠢的错误,另一双眼睛会帮助......我已经准备好放弃科学上我所知道的一切都是错的:)
以下是精神上令人厌恶的输出的上限:
答案 0 :(得分:2)
所以我想出了我的思考错误,并在下面写了一个简单的例子来解释我的困惑:希望这有助于其他人!
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;
的引用(很多人都使用 {{ 1}} )并且引用就在那里,尽管内联控制台命令行无法使用它。
欣赏导致答案的发人深省的思想!
我再次相信。