JS-构造函数

138 阅读2分钟

构造函数里的this

构造函数里的this指向实例化对象,而不是构造函数本身

function Car(){
    //this = {
	//    __proto__: Car.prototype,
    //    color: color
    //}
    this.color = 'red';
    
    //return this; 隐式添加,this返回到全局
}
Car();  // 未实例化的时候 this -> window
var car1 = new Car(); // this -> car1

步骤:

  1. 函数预编译加载的时候,有了GO,GO保存了Car
  2. Car()执行,生成AO
  3. 执行的时候发现有new关键字,自动保存this到AO里,this = {}
  4. 执行函数体的时候,往this添加属性和方法
  5. 全局中将实例化对象交给car1变量(隐式添加的return this),car1变量就成了一个对象,保存实例化对象中的属性和方法
GO = {
    Car: (function)  
    car1: {color: red}
}
AO = {
    this: {color: color}
}

当Car被实例化(new)的时候,就相当于普通函数被执行的,new只是改变了this指向。

function Car(color){
    var me = {};
    me.color = color;
    return me;
}
var car = Car('red');

自己手动加一个空对象是一样的结果

function test(){
    var obj = {
        name: 'jackson',
        age: 25
    }
    return obj;
}
var obj1 = test();
console.log(obj1.name);

和构造函数一样的作用

return this

function Car(){
    this.color = 'red';
    
    //return 123; -> red
    //return {}; -> {}
    //return []; -> []
    //return function(){}; -> function(){}
    //return this;
}
var car = new Car();
console.log(car);

return 是引用值的时候,可以替代隐式的this,原始值不行


例:

写一个构造函数,接收数字类型的参数,参数数量不定,完成参数相加和相乘的功能

function Compute(){
	var res = 0;
	this.plus = function(){
		loop(arguments, 'add', res);
	}
	this.times = function(){
		res = 1;
		loop(arguments, 'mul', res);
	}

	function loop(args, method, res){				
		for (var i = 0; i < args.length; i++) {
			var item = args[i];
			if (method === 'add') {
				res += item;
			}else if(method === 'mul'){
				res *= item;
			}					
		}
		console.log(res);
	}
}
var compute = new Compute();
compute.plus(2,2,2,2);
compute.times(2,2,2,2);

例:

写一个车的构造函数,可设置车的品牌,颜色,排量

再写一个消费者的构造函数,设置用户的名字,年龄,收入,通过选择的方法实例化该用户喜欢的车,再设置车发属性

function Car(opt){
	this.brand = opt.brand;
	this.color = opt.color;
	this.output = opt.output;
}
function Consumer(opt){
	this.name = opt.name;
	this.age = opt.age;
	this.income = opt.income;
	this.selectCar = function(){
		var myCar = new Car(opt.carOpt);//可连用
		console.log(this.name + '挑选了一辆排量为' + myCar.output + '的' + myCar.color + myCar.brand);
	}
}
var jackson = new Consumer({
	name: 'jackson',
	age: 25,
	income: '10k',
	carOpt: {
		brand: 'baoma',
		color: 'red',
		output: 2500
	}			
});
jackson.selectCar();

用apply做:

function Car(displacement, color, brand){
	this.displacement = displacement;
	this.color = color;
	this.brand = brand;
	this.info = function(){
		return '排量为'+ this.displacement +'的'+ this.color +'颜色的'+ this.brand;
	}
}
function Person(opt){
	Car.apply(this, [opt.displacement, opt.color, opt.branf]);
	this.age = opt.age;
	this.name = opt.name;
	this.buy = function(){
		console.log('年龄为'+ this.age + '岁姓名为'+ this.name+'买了一辆' + this.info());
	}
}

var jackson = new Person({
	age: 25,
	name: 'jackson',
	displacement: 2000,
	color: 'green',
	brand: 'benz'
});

jackson.buy();