Reputation: 18093
I'm to creating an object constructor with an object as one of it's properties, and want to add methods to that object's prototype.
Defining it like so doesn't work because the object is instantiated from an object literal and not from a constructor:
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);
},
}
Cutting to the chase and using __proto__
like so works, but __proto__
is depreciated.
__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);
},
}
Upvotes: 0
Views: 45
Reputation: 140210
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);
}
Upvotes: 2