首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Object.defaults对Object.prototype.defaults

Object.defaults对Object.prototype.defaults
EN

Stack Overflow用户
提问于 2014-01-29 04:40:45
回答 2查看 129关注 0票数 2

我很困惑什么时候使用.prototype来扩展对象,什么时候不使用它。和下面的部分代码一样,为什么不在.prototype中使用FacebookApi.defaults.prototype是否仅用于函数?

代码语言:javascript
复制
+function ($) { "use strict"; 
  var FacebookApi = function () { 
    return
  }  
  FacebookApi.defaults = {
    request_url: null
  }
  FacebookApi.prototype.request = function (options) {    
    $.ajax({
        url: options
      , cache: true
      , method: 'GET'
      , dataType: 'jsonp'
      , success: function (data) {
        FacebookApi.prototype.userinfo(data)
      }
    })
    return
  }
  window.facebookapi = new FacebookApi();

  $(document)
    .on('load', facebookapi);

}(window.jQuery);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-29 05:00:24

我不确定您的示例代码来自何处,但通常您希望使用prototype,如果您希望子类能够访问它,或者希望能够通过this访问它。

示例代码中的defaults将对应于Java中的一个static变量--它可以很容易地在类内或类之外引用,但是不能使用this.defaults来获取它。另外,子类无法覆盖,只能访问完全限定名(FacebookApi.defaults) --尽管在您的示例中,您在函数中声明了FacebookApi,因此只能在函数中看到。

希望这有助于澄清一点!

票数 1
EN

Stack Overflow用户

发布于 2014-01-29 05:21:14

代码语言:javascript
复制
var Person = function (name) {
    var person = this;
    person.name = name;
    person.breaths_taken = 0;
    person.next_breath;

    person.breathe();
};

Person.time_between_breaths   = 2300;
Person.last_person_to_breathe = null;
Person.last_person_to_die     = null;
Person.list_of_the_dead       = [];



Person.prototype.breathe = function () {
    var person = this,
        time_to_wait = Person.time_between_breaths;

    person.breaths_taken += 1;
    Person.last_person_to_breathe = person;
    person.next_breath = setTimeout(function () { person.breathe(); }, time_to_wait);
};

Person.prototype.die = function () {
    var person = this;
    person.isAlive = false;
    clearTimeout(person.next_breath);
    Person.last_person_to_die = person;
    Person.list_of_the_dead.push(person);
};


var bob    = new Person("Bob" ),
    doug   = new Person("Doug"),
    bernie = new Person("Bernie");

bernie.die();

console.log(Person.last_person_to_die.name); // Bernie

.prototype值是给每个实例的公共静态值,而构造函数上的属性/方法只是可从构造函数访问的公共属性,与向任何其他对象添加属性的方式相同。

它所帮助的是组织代码,在应该是公共的代码之间,并在一般情况下应用于类(但不应该给每个实例....like是对所有其他实例的数组的引用,或者是从这里开始每个新实例的构造函数应该被输入的配置数据,等等).

...while .prototype属性只是作为对每个实例的引用添加。

基本上,构造函数会说是for (var key in this.constructor.prototype) { this[key] = this.constructor.prototype[key]; }

上面的例子应该能很好地说明这一点,希望如此。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21422256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档