function Person(name) {
this.name = name
this.sayName = function() {
console.log(this.name)
}
}
const p1 = new Person('高秀')
const p2 = new Person('高秀')
p1.sayName() // 高秀
p2.sayName() // 高秀
console.log(p1.sayName === p2.sayName) //false
console.log(Person.prototype)
/*
* {constructor: ƒ}
* constructor: ƒ Person(name)
* __proto__: Object
*
* */
Print can be seen from the above results, create an instance of each, it will recreate a sayName function, which allows it takes some performance
class Student {
constructor(name) {
this.name = name
}
sayName() {
console.log(this.name)
}
}
const p3 = new Student('麦乐')
const p4 = new Student('麦乐')
p3.sayName() // 麦乐
p4.sayName() // 麦乐
console.log(p3.sayName === p4.sayName) // true
console.log(Student.prototype)
/*
*{constructor: ƒ, sayName: ƒ}
constructor: ƒ Student(name),
sayName: ƒ sayName(),
__proto__: Object
*/
Here we can see, the function of the class is created on the prototype, syaName method for each instance point to the same address, that is the same way with respect to the constructor, the performance will be increased.
Here are two similarities. this point is an instance of
function Person(name) {
this.name = name
this.sayName = function() {
console.log(this)
}
this.sayHello = function() {
const check = this.sayName
check()
}
}
const p1 = new Person('高秀')
const p2 = new Person('麦乐')
p1.sayName() // Person {name: "高秀", sayName: ƒ, sayHello: ƒ}
p2.sayName() // Person {name: "麦乐", sayName: ƒ, sayHello: ƒ}
p1.sayHello() // undefiend
class Student {
constructor(name) {
this.name = name
}
sayName() {
console.log(this)
}
sayHello() {
const checkThis = this.sayName
checkThis()
}
sayBind() {
const checkThisBind = this.sayName.bind(this)
checkThisBind()
}
}
const p5 = new Student('章三')
const p6 = new Student('历史')
p5.sayName() // Student {name: "章三"}
p6.sayName() // Student {name: "历史"}
p5.sayHello() // undefiend 这里可以解释为什么react中的事件调用函数需要绑定this
p5.sayBind() // Student {name: "章三"}