两次打印的this值为什么不同

var VElement=function(tagName,props,children){
        this.tagName=tagName;
        this.props=props||{};
        this.children=children||{};
        this.key=props?props.key:void 666;
        var count=0;
        console.log(this);
        $.each(this.children,function(i,child){
            console.log(this);
        });
        this.count=count;
    }

    var vdom=VElement('div',{'id':'container'},['最外层']);
阅读 2.9k
3 个回答

首先你要明白this是谁调用它它就指向谁。

在循环外面的那个consolethis因为是window调用了VElement这个函数,所以this指向window。

在循环里面$.eachthis做了修改变成了this.children,所以循环里面的consolethis是指向this.children即传进来的['最外层']

//$.each 对于遍历函数的 this 指向做了修改。

var VElement=function(tagName,props,children){
        this.tagName=tagName;
        this.props=props||{};
        this.children=children||{};
        this.key=props?props.key:void 666;
        var count=0;
        console.log(this);
        var _this=this;
        $.each(this.children,function(i,child){
            console.log(_this);
        });
        this.count=count;
    }

    var vdom=VElement('div',{'id':'container'},['最外层']);
    

$.each 对于遍历函数的 this 指向做了修改. 你可以这么书写:

// ...
var context = this;
$.each(this.children, function(i, child) {
    console.log(context);
});
this.count = count;
// ...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题