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

后端 未结 19 1452
庸人自扰
庸人自扰 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:43
    var Animal = function(options) {
        var name = options.name;
        var animal = {};
    
        animal.getName = function() {
            return name;
        };
    
        var somePrivateMethod = function() {
    
        };
    
        return animal;
    };
    
    // usage
    var cat = Animal({name: 'tiger'});
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 07:45
    var Student = (function () {
        function Student(firstname, lastname) {
            this.firstname = firstname;
            this.lastname = lastname;
            this.fullname = firstname + " " + lastname;
        }
    
        Student.prototype.sayMyName = function () {
            return this.fullname;
        };
    
        return Student;
    }());
    
    var user = new Student("Jane", "User");
    var user_fullname = user.sayMyName();
    

    Thats the way TypeScript compiles class with constructor to JavaScript.

    0 讨论(0)
  • 2020-11-22 07:47

    Because I will not admit the YUI/Crockford factory plan and because I like to keep things self contained and extensible this is my variation:

    function Person(params)
    {
      this.name = params.name || defaultnamevalue;
      this.role = params.role || defaultrolevalue;
    
      if(typeof(this.speak)=='undefined') //guarantees one time prototyping
      {
        Person.prototype.speak = function() {/* do whatever */};
      }
    }
    
    var Robert = new Person({name:'Bob'});
    

    where ideally the typeof test is on something like the first method prototyped

    0 讨论(0)
  • 2020-11-22 07:48

    You probably want to create a type by using the Folding Pattern:

        // Here is the constructor section.
        var myType = function () {
            var N = {}, // Enclosed (private) members are here.
                X = this; // Exposed (public) members are here.
    
            (function ENCLOSED_FIELDS() {
                N.toggle = false;
                N.text = '';
            }());
    
            (function EXPOSED_FIELDS() {
                X.count = 0;
                X.numbers = [1, 2, 3];
            }());
    
            // The properties below have access to the enclosed fields.
            // Careful with functions exposed within the closure of the
            // constructor, each new instance will have it's own copy.
            (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
                Object.defineProperty(X, 'toggle', {
                    get: function () {
                        var before = N.toggle;
                        N.toggle = !N.toggle;
                        return before;
                    }
                });
    
                Object.defineProperty(X, 'text', {
                    get: function () {
                        return N.text;
                    },
                    set: function (value) {
                        N.text = value;
                    }
                });
            }());
        };
    
        // Here is the prototype section.
        (function PROTOTYPE() {
            var P = myType.prototype;
    
            (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
                Object.defineProperty(P, 'numberLength', {
                    get: function () {
                        return this.numbers.length;
                    }
                });
            }());
    
            (function EXPOSED_METHODS() {
                P.incrementNumbersByCount = function () {
                    var i;
                    for (i = 0; i < this.numbers.length; i++) {
                        this.numbers[i] += this.count;
                    }
                };
                P.tweak = function () {
                    if (this.toggle) {
                        this.count++;
                    }
                    this.text = 'tweaked';
                };
            }());
        }());
    

    That code will give you a type called myType. It will have internal private fields called toggle and text. It will also have these exposed members: the fields count and numbers; the properties toggle, text and numberLength; the methods incrementNumbersByCount and tweak.

    The Folding Pattern is fully detailed here: Javascript Folding Pattern

    0 讨论(0)
  • 2020-11-22 07:48

    MooTools (My Object Oriented Tools) is centered on the idea of classes. You can even extend and implement with inheritance.

    When mastered, it makes for ridiculously reusable, powerful javascript.

    0 讨论(0)
提交回复
热议问题