Difference between reference and instance in javascript

后端 未结 8 2099
长情又很酷
长情又很酷 2020-12-23 23:10

Sometimes I hear people say \"a reference to a object\" and some say \"a instance of a object\" What is the difference?

8条回答
  •  渐次进展
    2020-12-23 23:22

    Instance of an object (or, perhaps more accurately phrased when talking about languages that have the notion, of a class) is an object that has been created and exists in memory. For example, when writing

    var obj = new Foo();
    

    Then a new instance of an object has been created (with new Foo).

    Reference to an object is some kind of handle that allows us to access an instance. For example, in many languages (including JavaScript) obj now holds a reference to the instance we just created.

    There can be many references to the same instance, as in

    var obj2 = obj;
    

    where now both obj and obj2 hold references to the same object.

提交回复
热议问题