functionPerson(name,age){ this.name = name this.age = age }
var p = new Person('Bob',18)
这样就简单地实现了一个类 如果要实现一些方法,也一样通过this指向
1 2 3 4 5 6 7 8 9 10 11
functionPerson(name,age){ this.name = name this.age = age this.greet = function(){ console.log(`Hello, I am ${this.name} and I am ${this.age} years old`) } }
var p = new Person('Bob',18) p.greet() // Hello, I am Bob and I am 18 years old
functionPerson(name,age){ this.name = name this.age = age } Person.prototype.greet = function(){ console.log(`Hello, I am ${this.name} and I am ${this.age} years old`) } var p = new Person('Bob',18) p.greet() // Hello, I am Bob and I am 18 years old
functionPerson(name,age){ this.name = name this.age = age functioncomplete(){ console.log('The object has been constructed') } complete() } var p = new Person('Bob',18) // The object has been constructed
classPerson{ constructor(name,age){ this.name = name this.age = age } }
这里说说使用class怎么实现类中的各种方法
静态方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classPerson{ constructor(name,age){ this.name = name this.age = age } static s(){ console.log('static') } }
let p = new Person('Bob',18) p.s() // Uncaught TypeError: p.s is not a function Person.s() // static
公有方法
1 2 3 4 5 6 7 8 9 10 11 12 13
classPerson{ constructor(name,age){ this.name = name this.age = age } greet(){ console.log(`Hello, I am ${this.name} and I am ${this.age} years old`) } }
let p = new Person('Bob',18) p.greet() // Hello, I am Bob and I am 18 years old
私有方法
ES6class并没有提供私有方法的直接实现,所以需要我们自己做一些变通处理
约定俗成
在使用时,我们默认把前面加上下划线_的方法看成私有方法
1 2 3 4 5 6 7 8 9
classPerson{ constructor(name,age){ this.name = name this.age = age } _p(){ console.log('private') } }