1、ES5实例化对象
在ES5中如果需要生成一个实例对象,那么需要有一个构造函数,通过构造函数实例化对象。
function Person(name,age) {
this.name = name
this.age = age
}
Person.prototype.say = function(){
return `I am ${this.name}.`
}
const person = new Person("Tom", 18)
console.log(person.say())
ES5实例化对象的过程
- 首先通过new关键字调用构造函数,后台会隐式执行new Object()创建对象即:创建一个以这个函数为原型的空对象
- 将构造函数的作用域给新对象,(即new Object()创建出的对象),而函数体内的this就代表new Object()出来的对象
- 执行构造函数的代码
- 返回新对象(后台直接返回)
2、ES6 Class
本质上,ES6 的类只是 ES5 的构造函数的一层包装,是基于javascript原型链机制开发的语法糖。类相当于实例的原型,所有在类中定义的方法,都会被实例继承。
class Person{
constructor(name,age){
this.name = name
this.age = age
}
say() {
return `I am ${this.name}`
}
getAge() {
return this.age
}
}
var person = new Person("Tom",18)
console.log(person.say())
constructor方法是类的构造函数的默认方法,通过new命令生成对象实例时,自动调用该方法。constructor方法如果没有显式定义,会隐式生成一个constructor方法。constructor方法默认返回实例对象this。constructor中定义的属性可以称为实例属性(即定义在this对象上),constructor外声明的属性都是定义在原型上的,可以称为原型属性(即定义在原型上)
class Person{
constructor(name,age){
this.name = name
this.age = age
}
say() {
return `I am ${this.name}`
}
}
const person = new Person(12,88)
console.log(person.hasOwnProperty("name"))
// true
console.log(person.hasOwnProperty("age"))
// true
console.log(person.hasOwnProperty("say"))
// false
3、prototype
构造函数的prototype属性,在类中依然存在,实质上类的所有方法都定义在prototype属性上,类的所有实例共享一个原型
class Person{
constructor(name,age){
this.name = name
this.age = age
}
say() {
return `I am ${this.name}`
}
getAge() {
return this.age
}
}
Person.prototype.getName = function () {
return this.name
}
Person.prototype.work = 'xxx'
var person = new Person("Tom", 18)
console.log(person.getName())
console.log(person.work)
4、静态方法
所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。如果静态方法包含this关键字,这个this指的是类,而不是实例
class Foo {
static bar() {
this.baz()
}
static baz() {
console.log('hello')
}
baz() {
console.log('world')
}
}
Foo.bar()
// hello
网友评论