构造函数:
一、ES6的书写方式:
class 类名{
constructor(...接收实例化对象传的实参){
this.XXX=形参 // 里面不需要标点符号
...
}
方法名(){ 函数体 }
}
例子:
class Person{
constructor({name,age,gender,money}){ // 构造器 语法糖
this.name=name // 不需要加标点符号
this.age=age
this.gender=gender
this.money=money
Person.prototype.className=200; // 这样也可以添加 但是最好写在外面 因为每次实例化都会调用 而且不好修改
}
// ES6 方法写在构造器外面 就会直接挂在原型上面 这样实例化的时候 不用每个都实例化
say(){
console.log(`我叫:${this.name},我有${this.money}元`);
}
// 外面添加原型属性 添加不了 会直接添加到语法糖里面 所以只能在外面加
className="F72";
}
let gf=new Person({name:"z3",age:18,gender:"male",money:111});
// 外面添加原型的属性 不能写在语法糖里面 优化性能 构造函数和实例化对象都可以添加
Person.prototype.className=200;
stu1.__proto__.className=200;
二、类的特点:
// 类的typeof 是function(因为 类 本身就是构造函数)
class Person {
}
let p1 = new Person();
console.log(typeof p1); // object
console.log(typeof Person); // function 因为类就是构造函数 所以输出 function
对象:万物皆对象(是类的具体表现)
类:是对象的抽象
ES6类的特点:
1、class声明的类 具有暂时性死区 要先声明后使用
2、class声明的类 不能当普通函数调用(即必须加new) 如果普通函数调用 会报错 没有 new
ES5 的构造函数 可以当普通函数调用 没有返回值 就会输出 un
3、class声明的类 返回值是引用数据类型 会覆盖this 基本数据类型不会覆盖 this
三、原型
构造函数.prototype 指向的是原型 共有的 构造函数都有的 是一个对象 存储共有的属性和方法
就不需要实例化的时候每次都实例化 实例化对象里面都存构造函数里面的所有
实例化对象 只能看到原型对象里面的 可以查找 但是不能修改 后期能够修改 输出实例化对象的时候 自己身上是没有原型对象的 只能去查找
function CreateStu({name,age,gender,money}){
// let this={}
// this={
// this.__proto__=CreateStu.prototype;
// }
this.name=name;
this.age=age;
this.gender=gender;
this.money=money;
this.say=function(){
console.log(`我叫:${this.name},我有${this.money}元`);
}
// return this;
}
// 原型添加属性
CreateStu.prototype.className=200;
// 原型添加方法
CreateStu.prototype.classActive=function(){
console.log(`比划我猜`);
}
// ES5 批量在原型添加属性和方法
Object.assign(CreateStu.prototype, {
name:"111",
say(){
}
}) // 因为构造函数.prototype 是对象 所以可以批量添加 后面可以在添加 但是注意后面会覆盖前面的对象
let stu1=new CreateStu({name:"xiaohai",age:18,gender:"male",money:111});
let stu2=new CreateStu({name:"xiaoting",age:16,gender:"famale",money:2222222});
stu1.say(); // 使用构造函数里面的方法 我叫:xiaohai,我有111元
stu2.say(); // 使用构造函数里面的方法 我叫:xiaoting,我有2222222元
console.log(CreateStu.prototype); // 构造函数指向原型 {className: 200, classActive: ƒ, constructor: ƒ}
console.log(CreateStu.prototype.className); // 构造函数使用原型的属性
console.log(CreateStu.prototype.classActive()); // 构造函数使用原型的方法 函数里面的语句也会输出 这个是拿方法的返回值 还会输出 un
console.log(stu1.__proto__); // 实例化对象指向原型 {className: 200, classActive: ƒ, constructor: ƒ}
console.log(stu1.className); // 实例化对象使用原型的属性
console.log(stu1.__proto__.className); // 这种方法也可以
console.log(stu1.classActive()); // 实例化对象使用原型的方法 函数里面的语句也会输出 这个是拿方法的返回值 还会输出 un
console.log(stu1.__proto__.classActive()); // 这种方法也可以