【7期】彻底搞懂JS原型继承之——new 关键字都干了啥

实例化构造函数,获取对象

  1. 新建了一个对象 obj
  2. 这个新对象被执行[[prototype]]连接,即将obj的_proto_指向构造函数的prototype对象
  3. 将构造函数的作用域赋值给obj,即将构造函数this指向obj
  4. 执行构造函数中的代码(为新对象obj添加属性)
  5. 如果函数没有返回其他对象,那么返回新对象 obj
// 定义构造函数
function Fa (attr1, attr2) {
    this.attr1 = attr1
    this.attr2 = attr2
    
    this.func = function () {
        console.log(`hello function`)
    }
}

// 构造函数的原型属性
Person.prototype.protoAttr = 'protoAttr'


// 实例化
let p = new Fa(1, 2)
//1.var obj = {};
//2.obj._proto_ =  Fa.prototype();
//3.Fa.call(obj,1, 2);
//4.obj.attr1=1,obj.attr2=2,obj.func=function () { console.log(`hello function`)},obj.__proto__.protoAttr = 'protoAttr'
//5.return obj

Tips:如果函数返回的是基本类型值,实际会生成一个对象,返回obj;如果是函数返回的是引用类型值,则实际返回的是该引用类型值.

关于返回对象

构造函数通常不使用return关键字,它们通常初始化新对象,当构造函数的函数体执行完毕时,它会显式返回。在这种情况下,构造函数调用表达式的计算结果就是这个新对象的值

function fn(){    this.a = 2; }
var test = new fn();
console.log(test);//{a:2}

如果构造函数使用return语句但没有指定返回值,或者返回一个原始值,那么这时将忽略返回值,同时使用这个新对象作为调用结果

function fn(){    this.a = 2;     return; }
var test = new fn();
console.log(test);//{a:2}

如果构造函数显式地使用return语句返回一个对象,那么调用表达式的值就是这个对象

var obj = {a:1};
function fn(){    this.a = 2;     return obj; }
var test = new fn();
console.log(test);//{a:1}

猜你喜欢

转载自blog.csdn.net/m0_38073011/article/details/108538267