Javascript 在object literal函数中访问Jquery对象变量

Javascript 在object literal函数中访问Jquery对象变量,javascript,jquery,scope,object-literal,Javascript,Jquery,Scope,Object Literal,我不明白为什么不能检查存储在变量中的jquery对象的.change()方法。这是语法错误吗?我失去了背景吗 这是我的密码: var MyObj = { //declaration reference : $('#reference'), observeReference : function() { //The following line is not tracking the .change() method. //Not su

我不明白为什么不能检查存储在变量中的jquery对象的.change()方法。这是语法错误吗?我失去了背景吗

这是我的密码:

var MyObj = {

    //declaration
    reference : $('#reference'),
    observeReference : function() {

        //The following line is not tracking the .change() method. 
        //Not sure why... And I didn't any get console error!
        this.reference.change(function() {
            var opt = $('#reference option:selected').text();

            if (opt === 'other' || opt === 'reference') {
                $('#input_other').fadeIn();
            } else{
                $('#input_other').fadeOut();
                $('#input_other_bx').val('');
            };
        }.bind(this));      
    },
    init: function() {
        this.observeReference();
    }
};

$(document).ready(function() {
     MyObj.init();
});
如果
$('#reference')
在文档准备就绪之前执行,它将得到一个
length=0
的jquery对象

init方法将在文档准备就绪后执行,所以在init方法中分配引用

var MyObj = {

//declaration
reference : null,
...

init: function() {
    this.reference = $('#reference');
    this.observeReference();
}

当声明您的
MyObj
时,您的
id=“reference”
元素可能不存在。也没有必要问我们“这是语法错误吗”;您只需检查开发人员工具控制台即可。@Phil是的,这应该是问题所在,在
init
范围中设置属性应该可以解决问题。您好@Phil,请注意。实际上,正如我在代码注释中所说,“……我没有得到任何控制台错误!”。但代码仍然没有运行,这就是我询问语法的原因。