variable binding inside an object

前端 未结 2 1002
借酒劲吻你
借酒劲吻你 2021-01-29 00:32

in this code below:

var a = 1;
var boat = { a:2, 
             innerBoat: {a:3, 
                        print(){console.log(a);},
                        },
            


        
2条回答
  •  礼貌的吻别
    2021-01-29 00:49

    In javascript, an object really is nothing more than a collection of data, like a dictionary in many other languages.

    var boat = new Object(); just creates an empty object, as if you did var boat = {};

    If you're looking for something more like , you may try using ES6 classes

    var a = 0
    class Boat {
      constructor() {
        this.a = 1;
      }
      print() {
        console.log(this.a);
      }
    }
    var boat = new Boat()
    boat.print();  //output: 2
    

提交回复
热议问题