JS 物件機制深剖 new 運算子

2021-09-08 16:21:40 字數 2903 閱讀 5402

newnewthe new operator

the production

newexpression : new newexpression

evaluate newexpression.

call getvalue(result(1)).

if type(result(2)) is not object, throw a typeerror exception.

call the [[construct]] method on result(2), providing no arguments (that is, an empty list of arguments).

return result(5).

回到上述定義,其大意是,new 後必須跟乙個物件並且此物件必須有乙個名為 [[construct]] 的內部方法(其實這種物件就是構造器),否則會丟擲異常,比如:

var str = "test";

var astr = new

str;

//ff 顯示「str is not a constructor」

//ie 顯示「物件不支援此操作」

var num = new number(999);

var anum = new

num;

//結果同上

如果符合以上條件,那麼引擎將呼叫其 [[construct]] 內部方法,並不提供入口引數。接下來便要考察此內部方法。

另外,下面一段是 new 運算子的帶參用法,由於和無參用法區別不大,讀者朋友可直接略過。

the production memberexpression : new memberexpression arguments is evaluated as follows:

evaluate memberexpression.

call getvalue(result(1)).

evaluate arguments, producing an internal list of argument values (11.2.4).

if type(result(2)) is not object, throw a typeerror exception.

if result(2) does not implement the internal [[construct]] method, throw a typeerror exception.

call the [[construct]] method on result(2), providing the list result(3) as the argument values.

return result(6).

when the [[construct]] property for a function object f is called, the following steps are taken:

create a new native ecmascript object.

get the value of the prototype property of the f.

if result(3) is not an object, set the [[prototype]] property of result(1) to the original object prototype object as described in 15.2.3.1.

if type(result(6)) is object then return result(6).

return result(1).

根據這些內容,我們完全可以構造乙個偽 [[construct]] 方法來模擬此流程(其實已有眾多前輩做過此工作):

function

myobject(age)

myobject.construct = function

() , constructor =myobject;

o.__proto__ =constructor.prototype;

//ff 支援使用者引用內部屬性 [[prototype]]

return

o;};

var obj1 = new myobject(10);

var obj2 = myobject.construct(10);

alert(obj2

instanceof

myobject);

//true

property

description

[[construct]]

constructs an object. invoked via the new operator. objects that implement this internal method are called constructors.

[[class]]

a string value indicating the kind of this object.

[[call]]

executes code associated with the object. invoked via a function call expression. objects that implement this internal method are called functions.

[[prototype]]

the prototype of this object.

js中的new運算子

function base var base new base alert typeof base object var base base alert typeof base string 由以上可知,如果函式返回值是number,string,boolen這樣的值型別,則通過new運算子可以返回...

js中 new運算子解密

new 為一元運算子 作用 後面只能跟函式,用來呼叫函式 使用new呼叫函式與直接呼叫函式的區別 function fn1 this指向的變化 var ret1 fn1 window var ret2 new fn1 fn1 返回值的變化沒有return console.log ret1 ret1 ...

定位new運算子

通常,new 從堆中分配記憶體,但它還有另一種稱為 定位 placement new 運算子,它可以讓我們指定要使用的位置。可以通過這個特性來設定記憶體管 理規程,處理需要通過特定位址進行訪問的硬體或在特定位置建立物件。要使用定位 new 特性,需要包含標頭檔案 new。使用定位 new 運算子時,...