gpt4 book ai didi

javascript - 为什么 'this' 不是我期望的那样?

转载 作者:行者123 更新时间:2023-11-30 17:21:30 25 4
gpt4 key购买 nike

为什么“这”不是我期望的那样?

一直认为我对 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'

我期望的函数实际上正在调用,我打开它并看到我可以访问来自 Drawing 调用的闭包定义的变量的 一些,但不是所有 或者至少看起来是这样。

请教育我,也许我犯了一个愚蠢的错误,另一双眼睛会有所帮助...我准备放弃科学,我知道的一切都是错误的:)

下面是精神冒犯输出的上限: Offensive Output, Parental Guidance Advised

最佳答案

于是我找出了自己的思路错误,在下面写了一个简单的例子来解释我的困惑:希望对大家有帮助!

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;
}
}

我用我预先定义的 var Drawing = this; 替换了我对 this 的引用(很多的人使用 var that = this) 的形式并且引用在那里,尽管它不可​​用于内联控制台命令行。

感谢引出答案的发人深省 session !

我又相信了。

关于javascript - 为什么 'this' 不是我期望的那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25066815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com