JS中的类
先看一段代码
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return '('+this.x+','+this.y+')';
}
}
var p = new Point(1,2);
学过了js中的原型链,现在又有了这种代码,所以说为什么还要学原型链。。。
学习原型链是有必要的,实际上js中的class只不过是原型链方式的语法糖,之所以这样写是为了好理解。也就是说以上代码将会被解释为原型链方式(以下代码)。
function Point(x,y){
this.x = x;
this.y = y;
}
Point.prototype.toString = function(){
return '('+this.x+','+this.y+')';
}
var p = new Point(1,2);
第二块代码完全可以实现第一块代码的功能。那么问题来了,class Point是个什么类型呢?
class Point{
//...
}
typeof Point // "function"
Point === Point.prototype.constructor //true
类的数据类型就是函数,类本身就指向构造函数。
再看一下类中的成员函数是如何实现的。
class Hello{
constructor(){
}
toString(){
}
toValue(){
}
sayHello(){
console.log("Hello");
}
sayGoodBye(){
console.log("GoodBye");
}
}
var hello = new Hello();
hello.sayHello();//"Hello"
hello.sayGoodBye();"GoodBye"
试想一下,直接用ES5写的话怎么实现?
没错,就是原型链继承。
function Hello(){}
Hello.prototype = {
constructor(){
},
toString(){
},
toValue(){
},
sayHello(){
console.log("Hello");
},
sayGoodBye(){
console.log("GoodBye");
}
}
实际没什么区别,只是更好的方便理解而已。
因为类中的方法都在prototype对象里,所以向类中添加方法就是再prototype里添加方法。
Object.assgin(Hello.prototype,{
fun1(){},
fun2(){}
})
此方法可以一次性向类中添加多个方法。并且可以动态添加方法,亲测。
今天就总结这么多吧。。Bye~