目录

  1. 1. 案例
  2. 2. 案例

转:
  js中的new做了什么?
new 操作符干了什么

1. 案例

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person () {
this.name = name;
this.age = age;
this.sex = sex

this.sayName = function () {
return this.name;
};
}

var person = new Person("tom", 21, "famle");

console.log(person.name);

  使用关键字new创建新实例对象经过了以下几步:

1
2
3
4
5
1. 创建一个新对象
2. 将新对象的_proto_指向构造函数的prototype对象
3. 将构造函数的作用域赋值给新对象 (也就是this指向新对象)
4. 执行构造函数中的代码(为这个新对象添加属性)
5. 返回新的对象

1
2
3
4
var Obj = {};

Obj._proto_ =  Person.prototype();
Person.call(Obj);

2. 案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function Person1(name){
this.name = name;
}
function Person2(name){
this.name = name;
return this.name;
}
function Person3(name){
this.name = name;
return new String(name);
}
function Person4 (name){
this.name = name;
return function () {
}
}
function Person5(name){
this.name = name;
return new Array();
}
const person1 = new Person1("yuer");//Person1 {name: "yuer"}

const person2 = new Person2("yuer");//Person2 {name: "yuer"}

const person3 = new Person3("yuer");//String {0: "y", 1: "u", 2: "e", 3: "r", length: 4, [[PrimitiveValue]]: "yuer"}

const person4 = new Person4("yuer");//function() {}

const person5 = new Person5("yuer");//[]

这里给出了5个例子,其实new操作符干了以下三步:

1
2
3
4
1.先创建了一个新的空对象
2.然后让这个空对象的__proto__指向函数的原型prototype
3.将对象作为函数的this传进去,如果return 出来东西是对象的话就
直接返回 return 的内容,没有的话就返回创建的这个对象

对应伪代码:

1
2
3
4
5
6
对于const a = new Foo();,new干了以下事情

const o = new Object();//创建了一个新的空对象o
o.__proto__ = Foo.prototype;//让这个o对象的` __proto__`指向函数的原型`prototype`
Foo.call(o);//this指向o对象
a = o;//将o对象赋给a对象