gpt4 book ai didi

javascript - 如何在 JavaScript 的构造函数中定义对象的原型(prototype)?

转载 作者:行者123 更新时间:2023-12-02 17:29:26 25 4
gpt4 key购买 nike

我要创建一个对象构造函数,并将一个对象作为其属性之一,并希望向该对象的原型(prototype)添加方法。

像这样定义它是行不通的,因为该对象是从对象文字而不是构造函数实例化的:

 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__ 的情况下添加到对象原型(prototype)?

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);
}

关于javascript - 如何在 JavaScript 的构造函数中定义对象的原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com