如何在JavaScript中的构造函数中定义对象的原型?

时间:2014-04-21 20:37:00

标签: javascript

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

如此定义它不起作用,因为该对象是从对象文字而不是从构造函数实例化的:

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

1 个答案:

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