javascript - 两次打印的this值为什么不同
怪我咯
怪我咯 2017-04-11 11:51:06
[JavaScript讨论组]
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('p',{'id':'container'},['最外层']);
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(3)
黄舟

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

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

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

ringa_lee

//$.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('p',{'id':'container'},['最外层']);
    
巴扎黑

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

// ...
var context = this;
$.each(this.children, function(i, child) {
    console.log(context);
});
this.count = count;
// ...
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号