构造函数

369 阅读1分钟

构造函数

  1. 构造函数与普通函数的区别就是调用方式不同

只要是通过new来调用的函数都可以把它称作构造函数,因此JavaScript中每一个函数都可以作为构造函数

  1. 一般构造函数手写字母都为大写,而普通函数为小写

一、new创建实例化对象的过程

function Person(){
    this.name="beatrix"
    this.age=20
}
var person = new Person()
  • person.constructor===Person
  • Person.prototype.constructor===Person

1.创建一个空对象{}

var person = {}

2.设置该对象的 proto ===Person.prototype person.__proto__=Person.prototype

3.this指向空对象,并且执行构造函数

Person.call(person)

4.若构造函数无返回值或者返回的是非引用类型值,就返回这个实例对象。若返回值是引用类型,则返回这个引用类型

二、实现new

function myNew (constructor, ...res){
	if (typeof (constructor)!=='function') {
    	return fasle
    }
    //1. 创建一个空对象
    var obj = {}
    //2.设置原型
    obj.__proto__ = constructor.prototype
    //3.改变this指向并执行构造函数
    var result = constructor.apply(obj,	res)
    //4.判断返回
    return result instanceof Object ? result : obj
}
function People(name, age) {
    this.name = name;
    this.age = age;
}
var obj1 = myNew(People,'Beatrix',21);
console.log(obj1);

上述使用到ES6解构

也可以使用arguments--->指的是传入的参数

function myNew (constructor){
    //3.改变this指向并执行构造函数
    var result = constructor.apply(obj, [].slice.call(arguments,1))
 
}