我要创建一个对象构造函数,并将对象作为其属性之一,并希望将方法添加到该对象的原型中。
如此定义它不起作用,因为该对象是从对象文字而不是从构造函数实例化的:
function Resource (options) {
this.self = this;
this.options = options || {};
.. other options. ...
// service object that I want to add functions to its prototype
this.service = {
request: new XMLHttpRequest(),
requestMethod: options.requestMethod ||'GET',
},
// using prototype actually creates an object called prototype
// as a property of the service object.
this.service.prototype = {
dataToNode: function(element, parent, data){
var toAppend = document.createElement(element);
toAppend.innerHTML = data;
return parent.appendChild(toAppend);
},
}
切入追逐并使用__proto__
之类的方式有效,但__proto__
已弃用。
__proto__
的情况下添加对象原型?function Resource (options) {
this.self = this;
this.options = options || {};
.. other options. ...
// service object that I want to add functions to its prototype
this.service = {
request: new XMLHttpRequest(),
requestMethod: options.requestMethod ||'GET',
},
// using __proto__ works but its deprciated
this.service.__proto__ = {
dataToNode: function(element, parent, data){
var toAppend = document.createElement(element);
toAppend.innerHTML = data;
return parent.appendChild(toAppend);
},
}
答案 0 :(得分:2)
function Service(options) {
this.request = new XMLHttpRequest();
this.requestMethod = options.requestMethod || 'GET';
}
Service.prototype.dataToNode = function(element, parent, data){
var toAppend = document.createElement(element);
toAppend.innerHTML = data;
return parent.appendChild(toAppend);
};
function Resource (options) {
this.options = options || {};
this.service = new Service(this.options);
}