如果抛开 Javascript 用于模拟 Java 类的复杂语法(如 new、Function Object、函数的 prototype属性等),原型系统可以说很简单:
- 如果所有对象都有私有字段[[prototype]],就是对象的原型。
- 读一个属性,如果对象本身没有,则会继续访问对象的原型,直到原型为空或者找到为止。
但在 ES6中,Javascript提供了一系列内置函数,已便更为直接的访问操作原型。
- Object.create 根据指定的原型创建新对象,原型可以是null;
- Object.getPrototypeOf 获得一个对象的原型
- Object.setPrototypeOf 设置一个对象的原型
利用这三个方法,我们可以完全抛开类的思维,利用原型来实现抽象和复用。
var cat = {say(){ console.log("meow~"); },jump(){ console.log("jump"); }}var tiger = Object.create(cat, {say:{writable:true,configurable:true,enumerable:true,value:function(){ console.log("roar!"); }}})var anotherCat = Object.create(cat);anotherCat.say();var anotherTiger = Object.create(tiger);anotherTiger.say();
ES6 中的类
在如何场景下,都推荐使用 ES6 的语法来定义类,而令 function 回归原有的函数语义。
基本用法:
class Rectangle {constructor(height, width) {this.height = height;this.width = width;}// Getterget area() {return this.calcArea();}// MethodcalcArea() {return this.height * this.width;}}
继承:
class Animal {constructor(name) {this.name = name;}speak() {console.log(this.name + ' makes a noise.');}}class Dog extends Animal {constructor(name) {super(name); // call the super class constructor and pass in the name parameter}speak() {console.log(this.name + ' barks.');}}let d = new Dog('Mitzie');d.speak(); // Mitzie barks.
