Javascript Object.defaults vs Object.prototype.defaults
我很困惑什么时候使用Javascript Object.defaults vs Object.prototype.defaults,javascript,oop,Javascript,Oop,我很困惑什么时候使用.prototype来扩展一个对象,什么时候不使用它。与下面的部分代码一样,为什么不在FacebookApi.defaults中使用.prototype,而将.prototype仅用于函数 +function ($) { "use strict"; var FacebookApi = function () { return } FacebookApi.defaults = { request_url: null } Faceboo
.prototype
来扩展一个对象,什么时候不使用它。与下面的部分代码一样,为什么不在FacebookApi.defaults
中使用.prototype
,而将.prototype
仅用于函数
+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);
我不确定示例代码来自何处,但如果希望子类能够访问它,或者希望通过
this
访问它,通常需要使用prototype
示例代码中的默认值
对应于Java中的静态
变量-可以在类内或类外轻松引用它,但不能使用this.defaults
获取它。此外,子类不能重写,只能访问完全限定名(FacebookApi.defaults
)——尽管在您的示例中,您在函数中声明了FacebookApi
,因此它只在函数中可见
希望这有助于澄清一点
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
值是公共静态值,它们被赋予每个实例,而放置在构造函数上的属性/方法只是可以从构造函数访问的公共属性,与向任何其他对象添加属性的方法相同
它所做的帮助是在应该是公共的代码之间组织代码,并应用于一般的类(但不应该提供给每个实例……比如对所有其他实例数组的引用,或者从现在起应该提供给每个新实例的构造函数的配置数据等等)
…而.prototype
属性只是作为对每个实例的引用添加的
基本上,构造函数会说for(这个.constructor.prototype中的var key){this[key]=this.constructor.prototype[key];}
上面的例子应该能很好地说明这一点。它来自我的上级。。。感谢它帮助
$(文档)代码>没有任何意义。