javascript - 如何解决this的指向问题
高洛峰
高洛峰 2017-04-11 12:11:42
[JavaScript讨论组]
function schema(arg1,arg2) {
    return this.init.call(this,arg1,arg2);
}

schema.prototype={
    init:function(a,b){
        this.a=a;
        this.b=b;
        this.arr=[];
    },
    test:function(){
        $(".selector").each(function () {
            var tt=$(this).text();
            //我想把遍历循环出来的值 tt push到 arr中   应该怎么写(或者说怎样才能使this指向schema)
        })
    }
}

var schemaObj=new schema(1,2);
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(4)
怪我咯
function schema(arg1,arg2) {
    return this.init.call(this,arg1,arg2);
}

schema.prototype={
    init:function(a,b){
        this.a=a;
        this.b=b;
        this.arr=[];
    },
    test:function(){
        var selectedValues=$(".selector").map(function () {
            var tt=$(this).text();
            return tt;
        }).get();
        this.attr=this.attr.concat(selectedValues);
    }
}

var schemaObj=new schema(1,2);
天蓬老师

 $(".selector").each(function () {
     console.log(this)
 })

此时this指向$(".selector")


 $(".selector").each(()=> {
     console.log(this)
 })

此时this指向schemaObj

其实都是this四大规则中的隐式绑定,只不过后者是es6箭头函数,this指向调用父函数的对象

this的具体指向规则可以参考我的博客

大家讲道理
function schema(arg1,arg2) {
    return this.init.call(this,arg1,arg2);
}

schema.prototype={
    init:function(a,b){
        this.a=a;
        this.b=b;
        this.arr=[];
    },
    test:function(){
        var that = this;
        $(".selector").each(function () {
            var tt=$(this).text();
            that.arr.push(tt);
        })
    }
}

var schemaObj=new schema(1,2);
阿神
function schema(arg1,arg2) {
    return this.init.call(this,arg1,arg2);
}

schema.prototype={
    init:function(a,b){
        this.a=a;
        this.b=b;
        this.arr=[];
    },
    test:function(){
        $(".selector").each(function (index,item) {
            var tt=$(item).text();
            this.arr.push(tt)
        }.bind(this))
    }
}

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

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