Javascript object creation using literals vs custom constructor functions

前端 未结 3 811
天命终不由人
天命终不由人 2021-01-07 02:01

I understand that there are multiple ways to create an object in javascript and I have been reading that object literal syntax is generally preferred. (Correct?)

Wha

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 02:08

    You can use the custom constructor function when you want to create instances of objects, similar to Java.

    For example:

    function MyObj(x){
       this.x = x;
    }
    
    MyObj.prototype.printX = function(){
       alert(this.x);
    }
    
    var obj1 = new MyObj("hello");
    var obj2 = new MyObj("hello2");
    obj1.printX();//prints hello
    obj2.printX();//prints hello2
    

    Now I have two instances of this object. If I used String literals I would need to clone the object into a new var in order to get another instance.

提交回复
热议问题