现在有一个对象如下:
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方法,但是会报错 }); } }
数据分析师2017-10-01 00:23:10
Front-end novices ask for help with object-oriented questions? -PHP Chinese website Q&A-front-end newbies asking for help with object-oriented questions? -PHP Chinese website Q&A
Let’s take a look and learn.
怪我咯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指向上层函数 }