JS: Modify Value/Pair in JS Object

后端 未结 4 1779
一个人的身影
一个人的身影 2021-01-22 17:10

I\'m trying to work out the best way to modify an object without writing out a similar object three times. So I have these three objects:

var object1 = {
    sta         


        
4条回答
  •  独厮守ぢ
    2021-01-22 17:35

    You can set the common properties to a prototype object. For Example:

    function ObjectMaker (typeVal) {
      this.type = typeVal;
    }
    
    ObjectMaker.prototype.start = "start";
    ObjectMaker.prototype.end = "end";
    
    var object1 = new ObjectMaker("1");
    var object2 = new ObjectMaker("2");
    

    gives

    > object1.start
    "start"
    > object1.end
    "end"
    > object1.type
    "1"
    

    You could pass in an object to the maker function if number of variables are more.

    Since the prototype is shared across objects, you will have a lighter memory footprint than having the same on each object.

提交回复
热议问题