Javascript object creation using literals vs custom constructor functions

前端 未结 3 808
天命终不由人
天命终不由人 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条回答
  •  猫巷女王i
    2021-01-07 02:28

    The preferred method would be to use JSON: var p = { "name":"Adam" };

    If you have a lot of member variables you need to initialize, or will be using a lot of objects (such as an array of them), etc. then it only makes sense to go ahead and create a function (constructor) which will do all of this for you. Unless you want your code to look like this:

    var a = { "name":"Adam", "age":23, "city":"Boston" };
    var b = { "name":"Jeff", "age":24, "city":"San mateo" };
    var c = { "name":"Aaliyah", "age":25, "city":"New York" };
    var d = { "name":"Mary", "age":26, "city":"Dallas" };
    

提交回复
热议问题