javascript中引用和实例之间的区别

| 有时我听到人们说“对对象的引用”,而有人说“对象的实例” 有什么区别?     
已邀请:
        变量将保存对对象实例的引用。 实际对象是一个实例。 用于访问对象的一个​​或多个变量保存对该对象的引用。     
        对象的实例(或者在谈论具有类的概念的语言时,也许更准确地措词)是已创建并存在于内存中的对象。例如,当写作
var obj = new Foo();
然后创建了一个新的对象实例(带有
new Foo
)。 引用对象是一种允许我们访问实例的句柄。例如,在许多语言(包括JavaScript)中,“ 2”现在拥有对我们刚刚创建的实例的引用。 对同一实例的引用可能很多,例如
var obj2 = obj;
现在,
obj
obj2
都拥有对同一对象的引用。     
        一个实例可以有很多引用。就像,有很多通往同一个地方的路径一样。
var x=\"string object\";
var y=x;
x
y
都是对同一对象实例的两个不同(但相等)的引用。     
        在javascript中,变量是对实际实例的引用
    // create a new object from the Object constructor
    // and assign a reference to it called `firstObjRef`
    var firstObjectRef = new Object();

    // Give the object the property `prop`
    firstObjRef.prop = \"im a property created through `firstObjRef`\";


    // Create a second reference (called `secondObjRef`) to the same object
    var secondObjRef = firstObjRef;
    // this creates a reference to firstObjRef,
    // which in turn references the object

    secondObjRef.otherProp = \"im a property created through `secondObjRef`\";


    // We can access both properties from both references
    // This means `firstObjRef` & `secondObjRef` are the same object
    // not just copies

    firstObjRef.otherProp === secondObjRef.otherProp;
    // Returns true
如果将变量传递给函数,这也将起作用:
    function objectChanger (obj, val) {
         // set the referenced object;s property `prop` to the referenced
         // value of `val`
         obj.prop = val;
    }

    // define a empty object outside of `objectChanger`\'s scope
    var globalObject = {};

    globalObject === {}; // true

    // pass olobalObject to the function objectChanger
    objectChanger(globalObject, \"Im a string\");

    globalObject === {}; // false
    globalObject.prop === \"Im a string\"; // true

    
        我们始终使用对对象的引用,而不能直接使用该对象,只能使用引用。对象实例本身在内存中。 当我们创建一个对象时,我们会得到一个参考。我们可以创建更多参考:
var obj = {}; // a reference to a new object
var a = obj; // another reference to the object
    
        对象是类的已占用内存。引用指向该内存,并且有一个名称(u可以将其称为变量)。例如, A a = new A(); 在这里,当我们编写“ new A();”时,系统中将占用一些内存。 \'a \'是指向该内存的引用(变量),用于访问该内存中存在的数据。 对象是有生命的,这意味着它已经占用了一些内存。 参考指向对象。 实例是引用的副本,它在某个时间点指向对象。 引用是一个指向对象的变量。对象是具有一些内存的类的实例,而实例是对象具有的变量和方法。 引用是指对象或变量的地址。 对象是类的实例,实例是类的代表,即对象 实例是在运行时创建的实际对象。     
        
Var a=\"myObject\";
var b=a;
在这里,变量“ 13”是实例,变量“ 14”是引用     
        \'instance \'和\'reference'的实际英语定义。 实例:某事的一个例子或单个事件。 参考:动作提及。 因此,考虑实际单词的这两个定义并将其应用于JavaScript场景,您可以了解每个概念的适用性。     

要回复问题请先登录注册