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

查看:96
本文介绍了javascript - 两次打印的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'},['最外层']);

解决方案

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

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

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

这篇关于javascript - 两次打印的this值为什么不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆