1.class函数
(重点讲述:
constructor 构造器,是一个指针,指向该对象是从哪个类中实例化出来的;
hasOwnProperty:判断该对象的对象是否在实例对象当中)
例:1.js
class Box{
// 构造器
constructor(){
this.userName = "laoliu";
}
run(){
console.log(13);
}
}
const box = new Box();
// console.log(box.__proto__.constructor === Box);// true
// console.log(box.hasOwnProperty("userName"));// true
// console.log(box.hasOwnProperty("age"));// false
// console.log(box.hasOwnProperty("run"));// false
console.log(box.__proto__ === Box.prototype);// true
box.__proto__.run(); // 13
例:2.js
( 重点讲述: in 不管再原型对象中,还是在实例对象当中,只要存在即是true)
class Desk {
constructor(){
this.age = 12;
this.run = function () { //注意:原型中还是实例中 this.run
console.log(this.age+90)
}
}
run(){
console.log(this.age);
}
}
const desk = new Desk();
console.log(desk) //Desk { age: 12, run: [Function] }
desk.run(); //102
desk.__proto__.run(); //undefined
// 不管在原型对象当中还是在实例对象当中,只要存在即是true
// console.log("age" in desk);// true
// console.log("run" in desk);// true
// console.log("lala" in desk);// false
例3:
(重点讲述:constructor内定义的属性是实例,外部定义的是原型当中)
class One{
//constructor内定义的属性是实例,外部定义的是原型当中
constructor(){
}
}
One.prototype.a = 1; //静态属性
Object.assign(One.prototype,{
b:2
})
const one = new One();
const two = new One();
console.log(one === two); //false
console.log(one.__proto__ === two.__proto__); //true
console.log(one.a); // 1
console.log(two.a); // 1
console.log(one.b)
例4:
(重点讲述: 继承 super( ))
class Father {
constructor(userName){
this.userName=userName;
}
}
class Child extends Father{
constructor(userName){
super(userName);// 调用父级的构造函数
}
}
const daWa = new Child("da wa");
console.log(daWa.userName); // da wa
例5:
(重点讲述: 静态方法 静态属性)
class Box {
static run(){
console.log("12345");
}
}
Box.userName = 12;
Box.run(); // 12345
console.log(Box.userName); //12