" var self = this"的神奇之处,了解范围和参考

时间:2016-10-17 09:31:43

标签: javascript scope

我不是javascript及其范围的新手,但我总是想知道为什么哎呀以下示例实际上有效。

// lets define some twist
var ScopeMagic = function() {
    // early reference, copy dat' value
    var self = this;
    // there is no real mystery yet...
    this.mysteryDepth = 0;

    // but we create one there...
    this.increase = function(depth) {
        // okay, its clear that the context is "this"
        setMystery(depth);
        return this;
    };

    // private function, setting a value to the "self" variable
    function setMystery(val) {
        // i though self would by a copy of "this" !
        // mother Mary, i'm using self. I could use this here, but
        //  for the sake of the demo using self on purpose
        self.mysteryDepth += parseInt(val);
    }
}

var perplexity = new ScopeMagic();
perplexity.increase(42);
console.log(perplexity);

我们得到以下结果。

enter image description here

它显然很有效,但是当我们通过使用对self的引用来设置它时,如何修改对象属性,this似乎是它自己的变量($('#myP').html(function(i, h) { return h.replace('+', '<br />+'); });的副本)?

0 个答案:

没有答案