Instantiating a javascript object and populating its properties in a single line

前端 未结 8 2067
清酒与你
清酒与你 2021-01-12 14:50

Is there a way I can do all of this in a constructor?

  obj = new Object();
  obj.city = \"A\";
  obj.town = \"B\";
相关标签:
8条回答
  • 2021-01-12 15:29
    function MyObject(params) {
        // Your constructor
        this.init(params);
    }
    
    MyObject.prototype = {
        init: function(params) {
            // Your code called by constructor
        }
    }
    
    var objectInstance = new MyObject(params);
    

    This would be the prototype way, which i prefere over plain object literals when i need more then one instance of the object.

    0 讨论(0)
  • 2021-01-12 15:30

    try this

    var obj = {
        city : "A",
        town : "B"
    };
    
    0 讨论(0)
  • 2021-01-12 15:30

    try this:

    function MyObject(city, town) {
      this.city = city;
      this.town = town;
    }
    
    MyObject.prototype.print = function() {
      alert(city + " " + town);
    }
    
    obj = new MyObject("myCity", "myTown");
    obj.print();
    
    0 讨论(0)
  • 2021-01-12 15:33

    Like so:

    var obj = {
        city: "a",
        town: "b"
    }
    
    0 讨论(0)
  • 2021-01-12 15:34
    function cat(name) {
        this.name = name;
        this.talk = function() {
            alert( this.name + " say meeow!" )
        }
    } 
    
    cat1 = new cat("felix")
    cat1.talk() //alerts "felix says meeow!"
    
    0 讨论(0)
  • 2021-01-12 15:37

    You can write your custom constructor :

    function myObject(c,t) {
        this.city = c;
        this.town = t;
    }
    
    var obj = new myObject("A","B");
    
    0 讨论(0)
提交回复
热议问题