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

标签 javascript object this

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

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

相关文章:

javascript - 正在加载图像,但 onload/onerror 未按预期工作

Java:如何初始化类型化对象列表?

javascript - 好的部分,增强类型

java - 如何打印我的 Java 对象而不得到 "SomeType@2f92e0f4"?

java - 在最终类的构造函数中使用 "this"

javascript - 在javascript中需要帮助包装函数并正确处理 "this"

javascript - 如何检测是否已在 chrome 中授予麦克风权限

javascript - 如何从具有多行的 HTML 表单动态地将多行插入到数据库中?

java - 使用 java 在 JavaScript 中创建文件

javascript - JS 中的数组 - 表示它是对象