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

Difference between reference and instance in javascript

本文关键字:之间 区别 实例 引用 javascript      更新时间:2023-09-26

有时我听到人们说"对对象的引用",有些人说"对象的实例"有什么区别?

变量将保存对对象实例引用。

实际对象是实例

用于访问对象的变量包含对该对象的引用

对象的实例(或者,在谈论有类概念的语言时,更准确地说是类)是一个已经创建并存在于内存中的对象。例如,在写入时

var obj = new Foo();

然后创建了一个对象的新实例(使用new Foo)。

对对象的引用是允许我们访问实例的某种句柄。例如,在许多语言(包括JavaScript)中,obj现在拥有对我们刚刚创建的实例的引用。

同一个实例可能有许多引用,如

var obj2 = obj;

其中现在CCD_ 3和CCD_。

一个实例可以有多个引用。这就像,嗯,很多条路通向同一个地方。

var x="string object";
var y=x;

xy都是对对象的同一实例的两个不同(但相等)引用。

我们总是使用对对象的引用,不能直接使用对象,只能使用引用对象实例本身在内存中

当我们创建一个对象时,我们会得到一个引用。我们可以创建更多参考:

var obj = {}; // a reference to a new object
var a = obj; // another reference to the object
对象是一个类占用的内存。引用指向该内存,并且它有一个名称(您可以将其作为变量调用)。例如A A=新的A();在这里,当我们写"new A();"时,系统中会占用一些内存。"a"是指向该内存的引用(变量),用于访问该内存中的数据。

对象是在它有生命的时候获得的,意味着它已经占用了一些内存。引用指向对象。实例是在某个时间点指向对象的引用的副本。

折射率是一个指向对象的变量。对象是具有一定内存的类的实例,实例是一个变量&对象具有的方法。

引用是指对象或变量的地址。对象是类的实例,实例表示类的代表,即对象

实例是在运行时创建的实际对象。

在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

"instance"answers"reference"的实际英文定义

实例:某事物的一个例子或单一事件。

引用:提及的动作。

因此,考虑到实际单词的这两个定义,并将其应用到JavaScript场景中,您可以了解每个概念是如何适应的。

Var a="myObject";
var b=a;

这里,变量a是一个实例,而变量b是一个引用