JavaScript返回默认值

时间:2014-09-03 12:13:21

标签: javascript function

我想创建一个像这样的函数库(类似于jquery正在做的)

var myLib = function (idOfAnElement){
  var myElement = document.getElementById(idOfAnElement);
  return{
    getHeight: function (){
      return myElement.style.height;
    },
    getWidth: function (){
      return myElement.style.width;
    }
  }
}

我的问题是,我不知道如何返回

myElement

默认情况下,如果没有其他函数,如

myLib('myId').getHeight; // Returns Height
myLib('myId')            // Is supposed to return the HTML-Element with id = 'myId' 

2 个答案:

答案 0 :(得分:0)

创建特权方法,返回私有 myElement属性本身的值

var myLib = function (idOfAnElement){
  var myElement = document.getElementById(idOfAnElement);

  return{
    getHeight: function (){
      return myElement.style.height;
    },
    getWidth: function (){
      return myElement.style.width;
    },
    getElement: function() {
      return myElement;
    }
  }
}

myLib('myId').getElement();

答案 1 :(得分:0)

只需将想要的方法添加到元素对象

即可实现所需

Javascript允许轻松地向现有对象添加方法,即使this指针也指向绑定对象。

var myLib = function (idOfAnElement){
  var myElement = document.getElementById(idOfAnElement);
  myElement.getHeight: function (){
      return this.style.height;
  }
  myElement.getWidth: function (){
      return this.style.width;
  }
  return myElement;
}

注意:虽然它有效但我不推荐它。 您需要注意不要覆盖现有的方法/字段,如果多个库采用相同的方法,则可能发生冲突。

这不是jQuery正在做的事情:他们创建了一个包装器对象。要从jQuery获取元素,您需要使用[0]例如$('#myEl')[0]