What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1704
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  梦如初夏
    2020-11-22 07:44

    I think you should read Douglas Crockford's Prototypal Inheritance in JavaScript and Classical Inheritance in JavaScript.

    Examples from his page:

    Function.prototype.method = function (name, func) {
        this.prototype[name] = func;
        return this;
    };
    

    Effect? It will allow you to add methods in more elegant way:

    function Parenizor(value) {
        this.setValue(value);
    }
    
    Parenizor.method('setValue', function (value) {
        this.value = value;
        return this;
    });
    

    I also recommend his videos: Advanced JavaScript.

    You can find more videos on his page: http://javascript.crockford.com/ In John Reisig book you can find many examples from Douglas Crockfor's website.

提交回复
热议问题