如何解决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(){
        $(".selector").each(function () {
            var tt=$(this).text();
            //我想把遍历循环出来的值 tt push到 arr中   应该怎么写(或者说怎样才能使this指向schema)
        })
    }
}

var schemaObj=new schema(1,2);
阅读 2.9k
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);
推荐问题