现在有一个对象如下:
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方法,但是会报错
});
}
}Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
前端新手求助面向对象问题?-PHP中文网问答-前端新手求助面向对象问题?-PHP中文网问答
围观一下哦,学习一下。
这个涉及到闭包和原型链
//方法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指向上层函数 }