Heim  >  Fragen und Antworten  >  Hauptteil

前端新手求助面向对象问题?

现在有一个对象如下:

var doc= $(document);
function people(){                        //一个people对象
this.name = li;
}
people.prototype = {                      //对象方法
    sayName: function(){
        console.log(this.name);
    }
    bindEvent: function(){                //绑定页面元素
        doc.delegate('button','click',function(){
            people.sayName();   //这里报错Uncaught TypeError: people.sayName is not a function
                                //这里想调用sayName方法,但是会报错
        });
    }
}


哈哈哈哈哈哈2773 Tage vor898

Antworte allen(2)Ich werde antworten

  • 数据分析师

    数据分析师2017-10-01 00:23:10

    前端新手求助面向对象问题?-PHP中文网问答-前端新手求助面向对象问题?-PHP中文网问答

    围观一下哦,学习一下。

    Antwort
    0
  • 怪我咯

    怪我咯2017-02-18 11:51:40

    这个涉及到闭包和原型链

    //方法1
    bindEvent: function() { //绑定页面元素
        doc.delegate('button', 'click', this.sayName.bind(this));//此处通过bind方法强制绑定this对象
    }
    //方法2
    bindEvent: function() { //绑定页面元素
        var _this = this;
        doc.delegate('button', 'click', function() {
            _this.sayName();
        });//此处通过变量存储this
    }
    //方法3
    bindEvent: function() { //绑定页面元素
        doc.delegate('button', 'click', () => this.sayName());//通过箭头函数,箭头函数的this指向上层函数
    }


    Antwort
    0
  • StornierenAntwort