class Animal { // 构造方法,实例化的时候会被调用,如果不指定,那么会有一个不带参数的默认构造函数 constructor(name, color) { this.name = name; this.color = color; } // toString 是原型对象上的属性 toString() { console.log('name: ' + this.name + ',color: ' + this.color); } } var animal = new Animal('dog', 'white'); animal.toString(); // name: dog,color: white console.log(animal.hasOwnProperty('name')); // true console.log(animal.hasOwnProperty('toString')); //false console.log(animal.__proto__.hasOwnProperty('toString')); //true class Cat extends Animal { constructor(action) { // 子类必须要在constructor中指定super方法,否则在新建实例的时候会报错 super('cat', 'white'); this.action = action; } toString() { super.toString(); } } var cat = new Cat('catch'); cat.toString(); console.log(cat instanceof Cat); // true console.log(cat instanceof Animal); // true
类的 prototype
属性和 __proto__
属性
class Animal { // 构造方法,实例化的时候会被调用,如果不指定,那么会有一个不带参数的默认构造函数 constructor(name, color) { this.name = name; this.color = color; } // toString 是原型对象上的属性 toString() { console.log('name: ' + this.name + ',color: ' + this.color); } } class Cat extends Animal { constructor(action) { // 子类必须要在constructor中指定super方法,否则在新建实例的时候会报错 super('cat', 'white'); this.action = action; } toString() { super.toString(); } } var cat = new Cat('catch'); console.log(Cat.__proto__ === Animal); // true console.log(Cat.prototype.__proto__ == Animal.prototype); // true
class Cat {} console.log(Cat.__proto__ === Function.prototype); // true console.log(Cat.prototype.__proto__ === Object.prototype); // true