“new” 都做了些啥以及this绑定?

本文解析了JavaScript中构造函数及new操作符的工作原理,包括如何创建对象实例、this关键字的使用及其在不同上下文中的行为表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当你使用new的时候,会:

  1. 创建一个新的空对象;
  2. this绑定到该对象;
  3. 添加一个名为__proto__的新属性,并且指向构造函数的原型(prototype);
  4. 返回该this对象。


执行new命令时的原理步骤:

  1. 创建一个空对象,作为将要返回的对象实例
  2. 将这个空对象的原型,指向构造函数的prototype属性
  3. 将这个空对象赋值给函数内部的this关键字
  4. 开始执行构造函数内部的代码

如果你没有特别理解,那么我们接下来用例子来详细解释。首先定义一个构造函数Student,该函数接收两个参数nameage

 function Student(name, age){
  this.name = name;
  this.age = age;
}复制代码

现在我们使用new来创建一个新的对象:

  var first = new Student('John', 26);复制代码

到底发生了什么呢?

  1. 一个新的对象创建,我们叫它obj
  2. this绑定到obj,任何对this的引用就是对obj的引用;
  3. __proto__属性被添加到obj对象。obj.__proto__会指向Student.prototype
  4. obj对象被赋值给first变量。

我们可以通过打印测试:

  console.log(first.name);
// John

console.log(first.age);
// 26复制代码

接下来深入看看__proto__是怎么回事。

原型(Prototype)

每一个JavaScript对象都有一个原型。所有的对象都从它的原型中继承对象和属性。

打开浏览器开发者控制面板(Windows: Ctrl + Shift + J)(Mac: Cmd + Option + J),输入之前定义的Student函数:

  function Student(name, age) {
  this.name = name;
  this.age = age;
}复制代码

为了证实每一个对象都有原型,输入:

  Student.prototype;
// Object {...}复制代码

你会看到返回了一个对象。现在我们来尝试定义一个新的对象:

  var second = new Student('Jeff', 50);复制代码

根据之前的解释,second指向的对象会有一个__proto__属性,并且应该指向父亲的prototype,我们来测试一下:

 second.__proto__ === Student.prototype
// true复制代码

Student.prototype.constructor会指向Student的构造函数,我们打印出来看看:

  Student.prototype.constructor;
//  function Student(name, age) {
//    this.name = name;
//    this.age = age;
//  }复制代码

好像事情越来越复杂了,我们用图来形象描述一下:

Student的构造函数有一个叫.prototype的属性,该属性又有一个.constructor的属性反过来指向Student构造。它们构成了一个环。当我们使用new去创建一个新的对象,每一个对象都有.__proto__属性反过来指向Student.prototype

这个设计对于继承来说很重要。因为原型对象被所有由该构造函数创建的对象共享。当我们添加函数和属性到原型对象中,其它所有的对象都可以使用。

在本文我们只创建了两个Student对象,如果我们创建20,000个,那么将属性和函数放到prototype而不是每一个对象将会节省非常很多的存储和计算资源。

我们来看一个例子:

  Student.prototype.sayInfo = function(){
  console.log(this.name + ' is ' + this.age + ' years old');
}复制代码

我们为Student的原型添加了一个新的函数sayInfo – 所以使用Student创建的学生对象都可以访问该函数。

  second.sayInfo();
// Jeff is 50 years old复制代码

创建一个新的学生对象,再次测试:

var third = new Student('Tracy', 15);// 如果我们现在打印third, 虽然只会看到年龄和名字这两个属性,// 仍然可以访问sayInfo函数。

var third = new Student('Tracy', 15);
// 如果我们现在打印third, 虽然只会看到年龄和名字这两个属性,
// 仍然可以访问sayInfo函数。
third;
// Student {name: "Tracy", age: 15}
third.sayInfo();
// Tracy is 15 years old
复制代码

在JavaScript中,首先查看当前对象是否拥有该属性;如果没有,看原型中是否有该属性。这个规则会一直持续,直到成功找到该属性或则到最顶层全局对象也没找到而返回失败。

继承让你平时不需要去定义toString()函数而可以直接使用。因为toString()这个函数内置在Object的原型上。每一个我们创建的对象最终都指向Object.prototype,所以可以调用toString()。当然, 我们也可以重写这个函数:

  var name = {
  toString: function(){
    console.log('Not a good idea');
  }
};
name.toString();
// Not a good idea复制代码

创建的name对象首先查看是否拥有toString,如果有就不会去原型中查找。









一、构造函数和new命令

1、构造函数

  • JavaScript语言的对象体系,不是基于“类”的,而是基于构造函数(constructor)和原型链(prototype)
  • 为了与普通函数区别,构造函数名字的第一个字母通常大写,比如: var Person = function(){ this.name = '王大锤'; }
  • 构造函数的特点:
    a、函数体内部使用了this关键字,代表了所要生成的对象实例;
       b、生成对象的时候,必需用new命令调用此构造函数

2、new

  作用:就是执行构造函数,返回一个实例对象 

var Person = function(name, age){
    this.name = name;
    this.age = age;
    this.email = 'cnblogs@sina.com';
    this.eat = function(){
        console.log(this.name + ' is eating noodles');
    }
}

var per = new Person('王大锤', 18);
console.log(per.name + ', ' + per.age + ', ' + per.email); //王大锤, 18, cnblogs@sina.com
per.eat();  //王大锤 is eating noodles复制代码

执行new命令时的原理步骤:

  1. 创建一个空对象,作为将要返回的对象实例
  2. 将这个空对象的原型,指向构造函数的prototype属性
  3. 将这个空对象赋值给函数内部的this关键字
  4. 开始执行构造函数内部的代码

注意点:当构造函数里面有return关键字时,如果返回的是非对象,new命令会忽略返回的信息,最后返回时构造之后的this对象;
  如果return返回的是与this无关的新对象,则最后new命令会返回新对象,而不是this对象。示例代码:

console.log('---- 返回字符串 start ----');
var Person = function(){
    this.name = '王大锤';
    return '罗小虎';
}

var per = new Person();
for (var item in per){
    console.log( item + ': ' + per[item] );
}
//---- 返回字符串 start ----
//name: 王大锤

console.log('----- 返回对象 start ----');
var PersonTwo = function(){
    this.name = '倚天剑';
    return {nickname: '屠龙刀', price: 9999 };
}
var per2 = new PersonTwo();
for (var item in per2){
    console.log(item + ': ' + per2[item]);
}
//----- 返回对象 start ----
//nickname: 屠龙刀
//price: 9999复制代码

如果调用构造函数的时候,忘记使用new关键字,则构造函数里面的this为全局对象window,属性也会变成全局属性,

则被构造函数赋值的变量不再是一个对象,而是一个未定义的变量,js不允许给undefined添加属性,所以调用undefined的属性会报错。

示例:

var Person = function(){ 
    console.log( this == window );  //true
    this.price = 5188; 
}
var per = Person();
console.log(price); //5188
console.log(per);  //undefined
console.log('......_-_'); //......_-_
console.log(per.price); //Uncaught TypeError: Cannot read property 'helloPrice' of undefined复制代码

为了规避忘记new关键字现象,有一种解决方式,就是在函数内部第一行加上 : 'use strict';

表示函数使用严格模式,函数内部的this不能指向全局对象window, 默认为undefined, 导致不加new调用会报错

var Person = function(){ 
    'use strict';
    console.log( this );  //undefined
    this.price = 5188; //Uncaught TypeError: Cannot set property 'helloPrice' of undefined
}

var per = Person(); 复制代码

另外一种解决方式,就是在函数内部手动添加new命令:

var Person = function(){ 
    //先判断this是否为Person的实例对象,不是就new一个
    if (!(this instanceof Person)){
        return new Person();
    }
    console.log( this );  //Person {}
    this.price = 5188; 
}

var per = Person(); 
console.log(per.price); //5188复制代码

二、this关键字

var Person = function(){
    console.log('1111'); 
    console.log(this); 
    this.name = '王大锤';
    this.age = 18;

    this.run = function(){
        console.log('this is Person的实例对象吗:' + (this instanceof Person) ); 
        console.log(this); 
    }
}

var per = new Person();
per.run();
/* 打印日志:
1111
Person {}
this is Person的实例对象吗:true
Person {name: "王大锤", age: 18, run: function}
*/

console.log('---------------');

var Employ = {
    email: 'cnblogs@sina.com',
    name: '赵日天',
    eat: function(){
        console.log(this);
    }
}

console.log(Employ.email + ', ' + Employ.name);
Employ.eat();
/* 打印日志:
---------------
cnblogs@sina.com, 赵日天
Object {email: "cnblogs@sina.com", name: "赵日天", eat: function}
*/复制代码

1、this总是返回一个对象,返回属性或方法当前所在的对象, 如上示例代码

2、对象的属性可以赋值给另一个对象,即属性所在的当前对象可变化,this的指向可变化

var A = { 
    name: '王大锤', 
    getInfo: function(){
        return '姓名:' + this.name;
    } 
}

var B = { name: '赵日天' };

B.getInfo = A.getInfo;
console.log( B.getInfo() ); //姓名:赵日天

//A.getInfo属性赋给B, 于是B.getInfo就表示getInfo方法所在的当前对象是B, 所以这时的this.name就指向B.name复制代码

3、由于this指向的可变化性,在层级比较多的函数中需要注意使用this。一般来说,在多层函数中需要使用this时,设置一个变量来固定this的值,然后在内层函数中这个变量。

示例1:多层中的this

//1、多层中的this (错误演示)
var o = {
    f1: function(){
        console.log(this); //这个this指的是o对象

        var f2 = function(){
            console.log(this);
        }();
        //由于写法是(function(){ })() 格式, 则f2中的this指的是顶层对象window
    }
}

o.f1();
/* 打印日志:
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
*/


//2、上面代码的另一种写法(相同效果)
var temp = function(){
    console.log(this);
}
var o = {
    f1: function(){
        console.log(this); //这个this指o对象
        var f2 = temp(); //temp()中的this指向顶层对象window
    }
}
o.f1(); 
/* 打印日志
Object {f1: function}

Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
*/
//表示上面两种写法是一样的效果,this的错误演示


//3、多层中this的正确使用:使用一个变量来固定this对象,然后在内层中调用该变量
var o = {
    f1: function(){
        console.log(this); //o对象
        var that = this;
        var f2 = function(){
            console.log(that); //这个that指向o对象
        }();
    }
}
o.f1();
/* 打印日志:
Object {f1: function}
Object {f1: function}
*/复制代码

示例2: 数组遍历中的this

//1、多层中数组遍历中this的使用 (错误演示)
var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){
        //第一个this指的是obj对象
        this.arr.forEach(function(item){
            //这个this指的是顶层对象window, 由于window没有email变量,则为undefined
            console.log(this.email + ': ' + item);
        });
    }
}

obj.fun(); 
/* 打印结果:
undefined: aaa
undefined: bbb
undefined: 333
 */

//2、多层中数组遍历中this的使用 (正确演示,第一种写法)
var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){
        //第一个this指的是obj对象
        var that = this; //将this用变量固定下来
        this.arr.forEach(function(item){
            //这个that指的是对象obj
            console.log(that.email + ': ' + item);
        });
    }
}
obj.fun(); //调用
/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333
 */


//3、多层中数组遍历中this正确使用第二种写法:将this作为forEach方法的第二个参数,固定循环中的运行环境
var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){
        //第一个this指的是obj对象
        this.arr.forEach(function(item){
            //这个this从来自参数this, 指向obj对象
            console.log(this.email + ': ' + item);
        }, this);
    }
}
obj.fun(); //调用
/* 打印日志:
大锤@sina.com: aaa
大锤@sina.com: bbb
大锤@sina.com: 333
 */


//4.箭头函数

var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){
        //第一个this指的是obj对象
        this.arr.forEach((item)=>{
            //这个this从来自参数this, 指向obj对象
            console.log(this.email + ': ' + item);
        });
    }
}
obj.fun(); //调用
VM83:8 大锤@sina.com: aaa
VM83:8 大锤@sina.com: bbb
VM83:8 大锤@sina.com: 333



//5. 使用bind

var obj = {
    email: '大锤@sina.com', 
    arr: ['aaa', 'bbb', '333'],
    fun: function(){
        //第一个this指的是obj对象
        this.arr.forEach(function(item){
            //这个this从来自参数this, 指向obj对象
            console.log(this.email + ': ' + item);
        }.bind(this));
    }
}
obj.fun(); //调用
VM122:8 大锤@sina.com: aaa
VM122:8 大锤@sina.com: bbb
VM122:8 大锤@sina.com: 333
undefined复制代码

4、关于js提供的call、apply、bind方法对this的固定和切换的用法

1)、function.prototype.call(): 函数实例的call方法,可以指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
  如果call(args)里面的参数不传,或者为null、undefined、window, 则默认传入全局顶级对象window;
  如果call里面的参数传入自定义对象obj, 则函数内部的this指向自定义对象obj, 在obj作用域中运行该函数

var obj = {};
var f = function(){
    console.log(this);
    return this;
}

console.log('....start.....');
f();
f.call();
f.call(null);
f.call(undefined);
f.call(window);
console.log('**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****');
f.call(obj);
console.log('.....end.....');

/* 打印日志:
....start.....
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
**** call方法的参数如果为空、null和undefined, 则默认传入全局等级window;如果call方法传入自定义对象obj,则函数f会在对象obj的作用域中运行 ****
Object {}
.....end.....
*/复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值