1. 传统JavaScript中
//先写函数
function Coder(name,age){
this.name = name;
this.age = age;
}
//然后通过prototype方法创建一个实例方法
Coder.prototype.conding= function(){
console.log("I am "+ this.age+" years old")
}
Coder.prototype.coding = function(){
console.log("I'm "+this.name+" I'm coding!");
}
//之后new一个对象,并通过这个对象调用这个类的实例方法:
var test = new Coder('Daniel','28');
test.coding();
test.conding();
++ 在上面的构造函数中写法是JavaScript自成一脉的,但是在ES6中采用了面向对的方式,引入class关键字,我们可以通过class关键字定义一个类:
2. 在ES6中
*constructor 方法是类的默认方法,通过 new 命令生成对象实例的时候,解释器会自动调用该方法。如果没有显示定义,则会自动添加一个空的 constructor 方法。在实例化对象的时候,使用 new 关键字,调用constructor 方法后,返回的实例对象,我们将它赋值给我们的目标变量。
/**
* 创建一个Person类
* 在这个类中先创建构造函数constructor()
* 然后在为这个类创建一些成员方法。
*/
class Person{
//构造函数
constructor(name,sex){
this.name = name;
this.sex = sex;
}
//成员方法
eating(){
console.log(this.name+" is eating lunch !");
}
sexing(){
console.log(this.name +" is "+this.sex);
}
}
//实例化
var person = new Person('金江璇','男');
//对成员方法的调用
person.eating();
person.sexing();
++ 这里可以用另一个方法来查看class的属性,这两行代码说明了 ES6 的类只是之前构造函数的另一种写法,类的数据类型就是函数(function),类本身就指向构造函数。
console.log(typeof(Person));
console.log(Person === Person.prototype.constructor);