[英]How to define the prototype of an object in a constructor in JavaScript?
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__
追逐并使用__proto__
就像这样有效,但是__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);
},
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.