财产如何作为一种方法?

时间:2014-01-30 04:02:31

标签: javascript jquery

我们经常执行一种方法来运行$('div').show();之类的功能。这里show方法会在调用div时显示div。但是$('div').length;呢?长度是属性而不是方法,但也用于获取div的大小。那么,该属性如何被称为方法?任何新的例子对我来说都会更加清晰。

2 个答案:

答案 0 :(得分:4)

jQuery集合只是元素的数组。 length属性来自数组。 jQuery在需要时更新长度。例如,使用非常简化版本的jQuery:

var $ = (function(){

  function jQuery(sel) {
    // an array to hold the elements queried from the DOM
    this.el = [].slice.call(document.querySelectorAll(sel));
    // set the length of the array
    // as a property on the current instance
    this.length = this.el.length;
  }

  jQuery.prototype = {
    // a method that does not modify the length
    show: function() {
      this.el.forEach(function(x){
        x.style.display = 'block';
      });
      return this;
    },
    // a method that modifies the length
    parent: function() {
      this.el = this.el.map(function(x){
        return x.parentNode;
      });
      this.length = this.el.length; // update length
      return this;
    }
  };  

  return function(sel) {
    return new jQuery(sel);
  };
}());

$('ul').length; //=> the constructor set up the length
$('ul li').parent().length //=> the parent method updated the length

答案 1 :(得分:2)

正如下面的评论中指出的那样,jQuery的length属性不是特殊属性:它只是jQuery上的常规数字属性。如果要查看相关证明,请打开控制台窗口(在已链接jQuery的站点上),然后键入以下内容:

Object.getOwnPropertyDescriptor($, 'length')

你会发现它只是一个普通的数字属性。

当你使用jQuery选择器时,它会针对DOM运行选择器并正确设置length属性:没有魔法。

但是,JavaScript确实可以拥有具有getset功能的属性,这是非常好的功能。

您可以将Object.defineProperty用于此目的:

var o = {}

Object.defineProperty(o, 'foo', {
    get: function() { return 'bar'; },
    set: function(val) { console.log('setting value to '+val); },
});

然后你可以把它称为财产:

o.foo             // returns 'bar'
o.foo = 'baz';    // prints to console

有关详细信息,请参阅MDN documentation

这是一个将颜色名称转换为RGB字符串的愚蠢示例:

Object.defineProperty(o, 'color', {
    get: function() { return this._color; },
    set: function(val) {
        if(val.match(/^#/)) this._color = val;
        switch(val){
            case 'red': this._color = '#f00'; break;
            case 'green': this._color = '#0f0'; break;
            case 'blue': this._color = '#00f'; break;
            case 'white': this._color = '#fff'; break;
            case 'black': this._color = '#000'; break;
        }
    },
});
相关问题