JS中New操作符做了什么

例 1

由以下两段代码可以看出,new 关键字帮我们做了:

  1. 创建 obj 对象
  2. 把新建的 obj 对象的_ _ proto__指向构造函数 Common 的 prototype
  3. 构造函数的作用域会指向实例本身(新对象),this 也指向新对象
  4. 执行构造函数内部的代码,将属性添加给 person 中的 this 对象。
  5. 不用手动 return,会自动返回新对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Common(id){
var obj={};
obj.__proto__=Common.prototype;
obj.id=id;
return obj;
}
Common.prototype.makeFun=function(){
console.log('想要重复使用的方法')
}
let arr=[];
for(let i=0;i<10;i++){
arr.push(Common(i))
}
console.log(arr);
1
2
3
4
5
6
7
8
9
10
11
function Common(id){
this.id=id;
}
Common.prototype.makeFun=function(){
console.log('想要重复使用的方法')
}
let arr=[];
for(let i=0;i<10;i++){
arr.push(new Common(i))
}
console.log(arr);

例 2

var obj = new Base();

new 操作符具体干了什么呢?其实很简单,就干了三件事情:

1
2
3
var obj={}
obj.__proto__=Base.prototype
Base.call(obj)
  1. 创建一个空对象 obj
  2. 把空对象的_ _ proto__成员指向了 Base 对象的 prototype 成员对象
  3. 把 Base 函数对象的 this 指针替换成 obj,然后再调用 Base 函数,于是我们就给 obj 对象赋值了一个 id 成员变量,这个变量的值是 base

如果给 Base.prototype 的对象添加一些函数:

1
2
3
Base.prototype.toString = function() {
return this.id;
}

那么当我们使用 new 创建一个新对象的时候,根据_ _ proto__的特性,toString 这个方法也可以做新对象的方法被访问到。于是我们看到了:

构造子中,我们来设置“类”的成员变量(例如:例子中的 id),构造子对象 prototype 中我们来设置‘类’的公共方法。于是通过函数对象和 Javascript 特有的_ _ proto__与 prototype 成员及 new 操作符,模拟出类和类实例化的效果。

例 3

1
2
3
4
5
6
7
8
9
10
function Person () {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () {
return this.name;
}
}
var person = new Person("tom", 21, "WEB");
console.log(person.name)
1
2
3
4
5
6
7
8
9
10
11
12
var person = {};
person._proto_ = Person.prototype;//引用构造函数的原型对象
Person.call(person);//将构造函数的作用域给person,即:this值指向person

Function.method("new", function () {
//新创建一个对象,它继承了构造器的原型对象。
var that = Object.create(this.prototype); //此时,this是指向Function构造器的。
//调用构造器,绑定this对象到新对象that上
var other = this.apply(that, argument); //此时,this对象指向that对象。
//如果它的返回值不是一个对象,就返回新的对象。
return (typeof other === "object" && other) || that;
});

通过 new 关键字创建某构造函数的新实例对象,就是将原型链与实例的 this 联系起来,this 指向这个新对象,同时也指向这个构造函数,并且 this 对象还是这个构造函数的实例。

如果没有使用 new 操作符,直接用构造函数创建新实例对象,那么 this 对象就指向了 window 对象,不会指向这个新对象的,不管给这个新对象添加什么属性,都没有用,是直接添加到了 window 对象上了。

参考 1 参考 2

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信