簡體   English   中英

new關鍵字如何迫使該關鍵字指向JavaScript中新創建的對象?

[英]how does new keyword force this keyword to point to the newly created object in JavaScript?

好的,我是javascript世界的初學者,因此我停止研究new關鍵字指向新創建的對象這一點,讓我們編寫一些代碼,然后提出我的問題。

function Employee(name) {
    this.name = name;
}

var x = new Employee("youhana");

盡管表達式未到達末尾,new關鍵字如何迫使該關鍵字指向x對象,我的意思是

var x = new Employee("youhana");

首先, =操作數將等待new Employee("youhana");的表達式求值的new Employee("youhana"); 要結束,則它將分配此表達式的最終值並將其放入將成為對象的x ,另一個示例:

function Book(){
**/*at this point, there's is no relation between the new object that will be created after this block of code ended, so how new keyword in this point knew that the new object  **will** be obj and **this** will point to it?*/**
}

var obj = new Book();

表達式的順序:

1)使用Constructor.prototype作為原型創建一個新的空對象

x=Object.create(Employee.prototype);

2)調用構造函數,將新對象綁定為:

Employee.call(x);

3)表達式返回

function new_obj(of){
  var obj=Object.create(of.prototype);
  of.call(obj);
  return obj;
}

var x=new_obj(Employee);
//equals
var x=new Employee();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM