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

后端 未结 19 1905
庸人自扰
庸人自扰 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 08:03

    Following are the ways to create objects in javascript, which I've used so far

    Example 1:

    obj = new Object();
    obj.name = 'test';
    obj.sayHello = function() {
        console.log('Hello '+ this.name);
    }
    

    Example 2:

    obj = {};
    obj.name = 'test';
    obj.sayHello = function() {
        console.log('Hello '+ this.name);
    }
    obj.sayHello();
    

    Example 3:

    var obj = function(nameParam) {
        this.name = nameParam;
    }
    obj.prototype.sayHello = function() {
        console.log('Hello '+ this.name);
    }
    

    Example 4: Actual benefits of Object.create(). please refer [this link]

    var Obj = {
        init: function(nameParam) {
            this.name = nameParam;
        },
        sayHello: function() {
            console.log('Hello '+ this.name);
        }
    };
    var usrObj = Object.create(Obj);  // <== one level of inheritance
    
    usrObj.init('Bob');
    usrObj.sayHello();
    

    Example 5 (customised Crockford's Object.create):

    Object.build = function(o) {
       var initArgs = Array.prototype.slice.call(arguments,1)
       function F() {
          if((typeof o.init === 'function') && initArgs.length) {
             o.init.apply(this,initArgs)
          }
       }
       F.prototype = o
       return new F()
    }
    MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}  // For example
    
    var userB = {
        init: function(nameParam) {
            this.id = MY_GLOBAL.nextId();
            this.name = nameParam;
        },
        sayHello: function() {
            console.log('Hello '+ this.name);
        }
    };
    var bob = Object.build(userB, 'Bob');  // Different from your code
    bob.sayHello();
    


    To keep answer updated with ES6/ ES2015

    A class is defined like this:

    class Person {
        constructor(strName, numAge) {
            this.name = strName;
            this.age = numAge;
        }
    
        toString() {
            return '((Class::Person) named ' + this.name + ' & of age ' + this.age + ')';
        }
    }
    
    let objPerson = new Person("Bob",33);
    console.log(objPerson.toString());
    

提交回复
热议问题