86 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
			
		
		
	
	
			86 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Markdown
		
	
	
	
	
	
# ES6的Class和普通构造函数对比
 | 
						||
 | 
						||
https://zhuanlan.zhihu.com/p/42409367
 | 
						||
 | 
						||
**JS构造函数**
 | 
						||
 | 
						||
```js
 | 
						||
function MathHandle(x,y) {
 | 
						||
    this.x = x;
 | 
						||
    this.y = y;
 | 
						||
}
 | 
						||
 | 
						||
MathHandle.prototype.add = function() {
 | 
						||
    return this.x + this.y;
 | 
						||
}
 | 
						||
var m = new MathHandle(1,2);
 | 
						||
console.log(m.add());
 | 
						||
```
 | 
						||
 | 
						||
**Class**
 | 
						||
 | 
						||
```js
 | 
						||
//ES6的语法糖,本质还是JavaScript面向对象那套东西。最终还是会转换成上面的代码
 | 
						||
//形式上强行模仿了java,c#,有点失去了JavaScript的个性
 | 
						||
class MathHandle {
 | 
						||
    constructor(x,y) {
 | 
						||
        this.x = x;
 | 
						||
        this.y = y;
 | 
						||
    }
 | 
						||
 | 
						||
    add() {
 | 
						||
        return this.x + this.y;
 | 
						||
    }
 | 
						||
}
 | 
						||
const m = new MathHandle(1,2);
 | 
						||
console.log(m.add());
 | 
						||
 | 
						||
console.log(typeof MathHandle) // 'function'
 | 
						||
console.log(MathHandle.prototype.constructor === MathHandle) //true
 | 
						||
//构造函数的显式原型对象等于实例的隐式原型对象
 | 
						||
console.log(m.__proto__ === MathHandle.prototype) // true
 | 
						||
```
 | 
						||
 | 
						||
**原生继承**
 | 
						||
 | 
						||
```js
 | 
						||
function Animal() {
 | 
						||
    this.eat = function() {
 | 
						||
        console.log('animal eat')
 | 
						||
    }
 | 
						||
}
 | 
						||
function Dog() {
 | 
						||
    this.break = function() {
 | 
						||
        console.log('dog bark');
 | 
						||
    }
 | 
						||
}
 | 
						||
Dog.prototype = new Animal();
 | 
						||
//哈士奇
 | 
						||
var hashiqi = new Dog();
 | 
						||
hashiqi.bark();
 | 
						||
hashiqi.eat();
 | 
						||
```
 | 
						||
 | 
						||
**Class继承**
 | 
						||
 | 
						||
```js
 | 
						||
class Animal {
 | 
						||
    constructor(name) {
 | 
						||
        this.name = name;
 | 
						||
    }
 | 
						||
    eat() {
 | 
						||
        console.log(this.name + 'eat');
 | 
						||
    }
 | 
						||
}
 | 
						||
class Dog extends Animal {
 | 
						||
    constructor(name) {
 | 
						||
        super(name);
 | 
						||
    }
 | 
						||
    say() {
 | 
						||
        console.log(this.name + 'say');
 | 
						||
    }
 | 
						||
}
 | 
						||
const dog = new Dog('哈士奇');
 | 
						||
dog.say();
 | 
						||
dog.eat();
 | 
						||
``` |