2022/2/20

一、JavaScript

1、构造函数

1.1实例化原理

function Car(color, brand) {
  this.color = color
  this.brand = brand
}
var car1 = new Car('red', 'banz')
var car2 = new Car('blue', 'mazda')
console.log(car1.color)//red
console.log(car2.brand)//mazda

被实例化的对象,构造函数里面的this一定是指向对象的,绝不是指向构造函数本身的。它必须通过new实例化对象,它才会去指向我们实例化对象,如果不实例化,它就指向window。

this指向实例化对象

1.2 构造函数中的this到底是怎么回事

当下面的car1被实例化的时候,其实就相当于普通的函数被执行的时候。这个时候的car1也有AO,这个AO时候的等于对象。这个AO存了一个this,赋值为空对象,

//AO={
//this:{}

//}
function Car(color,brand){
    //当它被实例化的时候,在这里默认this={}
    this.color=color
    this.brand=brand
}
var car1= new Car('red','banz')

当new的时候,就把里面都跑完了。

this={
    color:color,
    brand:brand
    
}

访问car1的时候,其实就是在GO里面访问属性值。

GO={
Car:(function),
   car1:{
    color:'red',
    brand:'banz',
}
} 	  	

AO={
 this:{}//实例化的时候,看见有new了,
 color:color,
    brand:brand
}
function Car(color,brand){
    //当它被实例化的时候,在这里默认this={}
    this.color=color
    this.brand=brand
    //隐式的加了个return this 
}
var car1= new Car('red','banz')--this//this就是car1

new就是改变了this指向,返回this对象

知识点:预编译是执行前一刻对代码进行的编译过程,执行上下文是代码运行时的上下文环境。

现在我自己var一个me空对象,偏不要this了

function Car(color,brand){
//this={}
    var me ={}
        me.color=color;
    	me.brand=brand;
	return me;
}
var car1=  Car('red','mazda')
console.log(car.color);//red
console.log(car.brand);//mazda

你会感觉到 构造函数实例化是一件很幼稚的事情。仅仅是系统内置给你一个new。

new的作用其实就是把this造出来以后,指向实例化。

如下:

function Car(color, brand) {
  //this={}
  var me = {
    name: 'sz',
    color: 'blue'
  }
  //   me.color = color
  //   me.brand = brand
  return me
}
var obj1 = Car()
console.log(obj1.name)//sz
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值