大学时候学C#时候经常用到class 而对JS中的class屁点不知道;
class Ball {
constructor(radius = 40, x = 0, y = 0, vx = 0, vy = 0) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = radius;
this.createTime = new Date();
this.color = parseColor(Math.random() * 0xffffff); // 调用编写的函数将传入的16进制数转化为RGB值
}
constructor构造方法:构建对象的实例(想到了原型链 ) :)
在使用new关键字生成对象时,constructor方法会被执行,最终return的结果就是生成的对象实例。
当一个类没有constructor方法时会自动生成一个空的constructor方法,返回结果为空。
用new关键字实例化对象时传入的参数会做为constructor构造函数的参数传入。
class Fn {
constructor(name) {
console.log('Instantiate objects:'+ name);
}
}
new Fn('testObj');
//Instantiate objects:testObj
ES6 的class可以看作只是一个语法糖,而类本身可以看作一个构造函数
class A {
hello() {}
}
typeof A //function
既然是构造函数,就可以new出一个实例,
class A {
hello() {}
}
console.log(new A());
类中声明的hello函数出现在了实例A的原型上,那么得出结论类中声明的函数实际上是绑定在原型上的,故上述代码等价于
class A {
hello() {}
}
// 等于
function A() {}
A.prototype.hello = function() {};