javascript - jQuery 覆盖原型(prototype)中的 'this'

标签 javascript jquery prototype

我已经声明了一个 JavaScript 对象:

function A(name){
    this.name=name
}

A.prototype.test=function(){
    console.log(this.name);
};

作为一个简单的示例,我设置了一个按钮,如果单击该按钮,应将变量输出到本地控制台日志:

<button id='test'>test</button>

脚本:

var t=new A('hello');
$('#test').click(t.test);

当我点击我想要的按钮this.name显示(在本例中为“hello”),而是 this指的是单击的按钮,而不是我创建的对象。

这当然是一个调试脚本。在现实生活中,我将一个函数绑定(bind)到 window.resize 事件,该事件将在调整大小时重新构建窗口。

有一个JSFiddle这说明了问题。

对此我有一个解决方案,即在对象的构造函数中声明调整大小(或单击函数)并使用 this 的替代名称。 ,就像这样( Here's the JSFiddle ):

function A(name){
    this.name=name

    var self=this;
    $("#test").click(function(){
        console.log(self.name);
    });
}

但我宁愿使用原型(prototype)并将函数绑定(bind)到对象的构造函数中。我如何使用原型(prototype)来做到这一点?

最佳答案

您可以使用bind ,这将提前设置 this 的值:

var t=new A('hello');
$('#test').click(t.test.bind(t));

关于javascript - jQuery 覆盖原型(prototype)中的 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758753/

相关文章:

javascript - 提供 HTML 内容

javascript - 在 AngularJS 中包装 HighChart

asp.net - 服务器事件后禁用和启用 jquery 中的按钮

javascript - 原型(prototype)框架或包含在js中

javascript - Safari overflow-x hidden 导致内部固定元素困惑

javascript - Backbone.js - 给定一个元素,我如何获得 View ?

javascript - 如何悬停内容,排除某些 div 类

jquery - 下拉子菜单在 IE10 上很早就消失无法悬停在子菜单上

新对象构造函数中的Javascript新数组原型(prototype)

javascript - 将一个函数的原型(prototype)设置为另一个函数的原型(prototype)以进行子类化(使用 Object.setPrototypeOf()))