Constructors in JavaScript objects

后端 未结 19 2129
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  甜味超标
    2020-11-22 10:38

    I found this tutorial very useful. This approach is used by most of jQuery plug-ins.

    http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html#fbid=OVYAQL_TDpK

    var Class = function(methods) {   
        var klass = function() {    
            this.initialize.apply(this, arguments);          
        };  
    
        for (var property in methods) { 
           klass.prototype[property] = methods[property];
        }
    
        if (!klass.prototype.initialize) klass.prototype.initialize = function(){};      
    
        return klass;    
    };
    

    Now ,

    var Person = Class({ 
        initialize: function(name, age) {
            this.name = name;
            this.age  = age;
        },
        toString: function() {
            return "My name is "+this.name+" and I am "+this.age+" years old.";
        }
    }); 
    
    var alice = new Person('Alice', 26);
    alert(alice.name); //displays "Alice"
    alert(alice.age); //displays "26"
    alert(alice.toString()); //displays "My name is Alice and I am 26 years old" in most browsers.
    //IE 8 and below display the Object's toString() instead! "[Object object]"
    

提交回复
热议问题