说明
ES6 从入门到精通系列(全23讲)学习笔记。
es5 造类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function Person(name, age) { this.name = name; this.age = age; } Person.prototype.getName = function() { return this.name; } Person.prototype.getAge = function() { return this.age; } let kaimo = new Person("kaimo", 313); console.log(kaimo); console.log(kaimo.getName()); console.log(kaimo.getAge()); </script> </body> </html>
class 造类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> class Person { // 实例化的时候会被立即调用 constructor(name, age) { this.name = name; this.age = age; } getName() { return this.name; } getAge() { return this.age; } } let kaimo = new Person("kaimo", 313); console.log(kaimo); console.log(kaimo.getName()); console.log(kaimo.getAge()); </script> </body> </html>
这里添加方法还可以使用 Object.assign()
一次性向类中添加多个方法。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> class Person { // 实例化的时候会被立即调用 constructor(name, age) { this.name = name; this.age = age; } } Object.assign(Person.prototype, { getName() { return this.name; }, getAge() { return this.age; } }) let kaimo = new Person("kaimo", 313); console.log(kaimo); console.log(kaimo.getName()); console.log(kaimo.getAge()); </script> </body> </html>