简体   繁体   中英

Best practice for declaring JavaScript objects with similar properties

For a client side JS application, I require creating Quizzes and Surveys. The domain logic for these objects is incredibly similar so I would like them to both inherit from one UserInput object, while they each have very few additional methods each.

I'm concerned with the best practice method of doing this. I was thinking right off the top of my head I can just create a UserInput constructor that acts as a prototype, and then dynamically add methods to both Quizzes and Surveys.

For instance:

function UserInput() {}
UserObject.prototype.sharedMethod = function() {}

Quiz = new UserInput();
Quiz.sharedMethod()
Quiz.quizMethod = function() {}

Survey = new UserInput();
Survey.surveyMethod = function() {}

Survey.sharedMethod()

However I wonder if this is just not plain monkey-patching, and implementing a similar idea to abstract classes in JavaScript would be cleaner.

var Quiz = function() {
 UserInput.apply(this, arguments)
}
Quiz.prototype = UserInput();
Quiz.prototype.constructor = quiz;
Quiz.prototype.quizMethod = function() {}

The immediate difference I see is in the first example quiz/survey are objects while in the second quiz is a prototype. Every page has a singleton of these items, so having a method on every instance of quiz (which is only one) does not seem that bad to me.

Which is preferred and why? (Or am I missing any better methods of instantiating objects).

The one I use is available on github and it works well for me with a simple familiar sytax. Allows OOP concepts in javascript including classes, inheritance, multi-inheritance, polymophism, interfaces (code contracts), and enumerators

Heres an example of simple class inheritance:

/* using ds.oop.min.js */

var a= ds.class({
    type: 'a',
    constructor: function (x) { this.x = x; },
    mul: function (s) {
        this.x *= s;
        return this;
    }
});
var b= ds.class({
    type: 'b',
    inherits: a,              
    constructor: function (x) { this.x = x; },
    sub: function (s) {
        this.x -= s;
        return this;
    }
});
var o = new b(5);
var output = o.mul(3).sub(5);    // output = 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM