JavaScript对象引用问题 [英] JavaScript Object reference problem

查看:70
本文介绍了JavaScript对象引用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的html表单,带有一个数字输入和两个选择框。我正在尝试练习javascript的一些对象方法来创建一个单位转换器。我的js代码如下。它给出了未被引用的引用:fromUnit undefined的常量错误。两个选择框参考都会出现此错误。



Js Bin代码视图链接: http://jsbin.com/ ubeqex / 2 / edit [ ^ ]





I have a simple html form with one number input and two select boxes. I''m trying to practice some object methods of javascript to create a unit converter. My js code is as follows. It gives a constant error of "uncaught reference : fromUnit undefined". This error comes for both select box references.

Js Bin code view link : http://jsbin.com/ubeqex/2/edit[^]


var unitConvert = {
   
    //get values from the htmlform:
    fromLength:  document.getElementById('fromLength'), //;.value,
    toLength: document.getElementById('toLength').value,
    fromUnit: document.getElementById('fromUnits'),
    toUnit: document.getElementById('toUnits').selectedIndex,
   

unitLength: function() {
     
    
        console.log("in function");
         console.log(fromLength.value);  //this works fine.
         console.log(fromUnit);  //this gives error. IF I can access fromLength,   
         console.log(toUnit);  //this gives error. why not these two?
        
}
};

function addEvent(obj, type, fn) {
   if(obj && obj.addEventListener) {
       obj.addEventListener(type,fn,false);
   } else if( obj && obj.attachEvent) {
       obj.attachEvent('on' + type, fn);
   }
}
    
window.onload = function() {
   'use strict';
   
   
    var fromUnit = document.getElementById('fromUnits');
    var toUnit = document.getElementById('toUnits').selectedIndex;
    
   addEvent(fromLength, 'change', unitConvert.unitLength); //this works fine.        addEvent(fromUnit, 'change', unitConvert.unitLength);  
   addEvent(toUnit, 'change', unitConvert.unitLength); 
   }   

推荐答案

我认为,当事件被调用时,你不在unitConvert变量的上下文中。 br />


Moover,从代码看起来 fromLength 是一个全局变量,至少我看不到它的'初始化



I think, you are not in context of unitConvert variable, when event get''s called.

Moover, From code it looks fromLength is some global variable, at least I do not see it''s initialization

addEvent(fromLength, 'change', unitConvert.unitLength); //this works fine.





因为这是全局变量,你的代码工作正常





As this is global variable, your code works fine

console.log(fromLength.value);  //this works fine


这篇关于JavaScript对象引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆