javascript - JS/jQuery 原型(prototype)问题,可能的范围问题

标签 javascript jquery

感谢您的阅读。我有一个 jQuery 函数,我想制作原型(prototype)。该函数只是将隐藏/显示函数绑定(bind)到复选框。每个复选框对应于要隐藏的不同元素。我一直在进行控制台日志记录,并且正在创建对象;控制台上没有抛出其他错误。此功能的工作原理:

$("input[name='fcrBox']").bind('change', function(){
    if( $(this).is(':checked')){
        $("#result").show();
    } else {
        $("#result").hide();
    }
});

但这并不:

function HideShow(elem, affected) {
this.elem = elem;
this.affected = affected;
}

var fcrBox = new HideShow('input[name="fcrBox"]', '#result');
var sc = new HideShow('input[name="sc"]', '#MQSresult');

console.log(fcrBox);
console.log(sc);

HideShow.prototype.binder = function(elem, affected){
    $(elem).bind('change', function(){
        if( $(this).is(':checked')){
            $(affected).show();
        } else {
        $(affected).hide();
        }
    });
}

fcrBox.binder();
sc.binder();

谢谢!任何意见将不胜感激。

最佳答案

您使用两个参数(elemaffected)定义了 binder,但在调用该方法时没有传递任何值。

如果您想要访问已传递给构造函数并分配给对象的值,则必须显式访问这些值。这些值不会神奇地传递给 binder

function HideShow(elem, affected) {
    this.elem = elem; // <-----------------------------------------------|
    this.affected = affected;                                         // |
}                                                                     // |
                                                                      // |
var fcrBox = new HideShow('input[name="fcrBox"]', '#result');         // |
var sc = new HideShow('input[name="sc"]', '#MQSresult');              // |
                                                                      // |
console.log(fcrBox);                                                  // |
console.log(sc);                                                      // |
                                                                      // |
HideShow.prototype.binder = function(){                               // |
    var self = this; // reference to the instance; this is the same as --|
    $(self.elem).bind('change', function(){
        // In the event handler, `this` refers to the DOM element, not the
        // `HideShow` instance. But we can access the instance via `self`.
        if( $(this).is(':checked')){ // shorter: this.checked
            $(self.affected).show();
        } else {
            $(self.affected).hide();
        }
    });
}

fcrBox.binder();
sc.binder();

关于javascript - JS/jQuery 原型(prototype)问题,可能的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18338858/

相关文章:

javascript - 使用 react-router,redux 将无法工作

javascript - 设置间隔和 Internet Explorer

javascript - 使用 javascript/jquery 刷新 iframe 中的当前页面

javascript - 是否可以同时使用 JQuery 和 Zepto 库?

javascript - 集成 Jest 和 Rewire

javascript - Vue.js - axios 在尝试存储和显示 vue-axios 响应数据时未定义

javascript onclick滚动到中间页面上的div?

javascript - 在悬停时显示图像只是为了实际悬停的元素

javascript - 如何使自动框阴影变色

javascript - ES6 : Why Symbol can not have another symbol as description?