先看普通的构造函数
function Person(name,age) {
this.name=name;
this.age=age;
}
其实在new的过程中内部实现了隐式创建对象
function Person(name,age) {
//this={};隐式执行让this等于一个对象
this.name=name;
this.age=age;
//return this 隐式返回了this
}
new Person;
下面来写一个函数来实现new的作用
function Animal(name,sex) {
this.name=name;
this.sex=sex;
}
Animal.prototype.call=function (){
console.log('I am a '+this.name+',and I am a '+this.sex)
}
function newObj(obj,...rest) {
const newObj={};//创建新对象
newObj.__proto__=Animal.prototype;//让对象的原型指向Animal构造函数
Animal.apply(newObj,rest);//让构造函数的this指向新的对象,并传递参数
return newObj
}
const obj1=newObj(Animal,'老虎','male');
const obj2=newObj(Animal,'狐狸','female');
ES6的class
JavaScript中其实是没有class这个概念的,JavaScript的继承都是基于原型链, 所谓的class实际上是构造函数的语法糖。
class Person {
constructor(age, name) {
this.age = age
this.name = name
}
selfIntroduction() {
console.log(`I am ${this.name} and I am ${this.age} years old!`)
}
}
const xiaoMing = new Person(18, '小明')
// 上面的Person类实际上也是个函数,在new的过程中把属性挂载到实例上,把方法挂载到原型上