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

后端 未结 19 1667
庸人自扰
庸人自扰 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:58

    A base

    function Base(kind) {
        this.kind = kind;
    }
    

    A class

    // Shared var
    var _greeting;
    
    (function _init() {
        Class.prototype = new Base();
        Class.prototype.constructor = Class;
        Class.prototype.log = function() { _log.apply(this, arguments); }
        _greeting = "Good afternoon!";
    })();
    
    function Class(name, kind) {
        Base.call(this, kind);
        this.name = name;
    }
    
    // Shared function
    function _log() {
        console.log(_greeting + " Me name is " + this.name + " and I'm a " + this.kind);
    }
    

    Action

    var c = new Class("Joe", "Object");
    c.log(); // "Good afternoon! Me name is Joe and I'm a Object"
    

提交回复
热议问题