ES6提供了更接近传统语言的写法,引入了class
(类)这个概念。新的class
写法让对象原型的写法更加清晰、更像面向对象编程的语法,也更加通俗易懂。class
为构造函数的语法糖,即class
的本质是构造函数。class
的继承extends
本质为构造函数的原型链的继承。
一 . 构造函数
constructor方法,这就是构造方法,而this关键字则代表实例对象。简单地说,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的。
class king {
constructor(name) {
this.name=name;
}
run(){
console.log(this.name);
}
}
let num1 = new king("大王");
num1.run();
二. 继承
class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
console.log(this.type + ' says ' + say)
}
}
let animal = new Animal();
animal.says('hello'); //输出:animal says hello
class Cat extends Animal {
constructor(){
super();
this.type = 'cat';
}
}
let cat = new Cat();
cat.says('hello') ; //输出:cat says hello
三. 示例
- 原始构造函数
// 父类
function User(name, age) {
this.name = name;
this.age = age;
}
// 原型方法
User.prototype.changName = function (name) {
this.name = name;
};
User.prototype.changAge = function (age) {
this.age = age;
};
// 静态方法
User.getName = function () {
return "User";
};
// 取值方法
Object.defineProperty(User.prototype, "info", {
get() {
return "name:" + this.name + " | age:" + this.age;
},
});
var user = new User("cuiht", 23);
console.log(user);
// 子类
function Manager(name, age, passWord) {
User.call(this, name, age);
this.passWord = passWord;
}
// 继承父类静态方法
Manager._proto_ = User;
// 继承父类 prototype 原型方法
Manager.prototype = User.prototype;
// 添加新方法
Manager.prototype.changPassWord = function (passWord) {
this.passWord = passWord;
};
var manager = new Manager("cuiht", 23, "123456");
manager.changName("hunter");
console.log(manager);
- class类
// 父类
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 原型方法
changName (name) {
this.name = name;
};
changAge (age) {
this.age = age;
};
// 静态方法
static getName(){
return "User";
}
// 取值方法
get info(){
return "name:" + this.name + " | age:" + this.age;
}
}
var user = new User("cuiht", 23);
console.log(user);
class Manager extends User{
constructor(name,age,passWord){
super(name,age);
this.passWord = passWord;
}
changPassWord (passWord) {
this.passWord = passWord;
};
// 获取父类方法 示例
get newInfo(){
let info = super.info;
console.log(info);
return info + '--- new';
}
}
var manager = new Manager("cuiht", 23, "123456");
manager.changName("hunter");
console.log(manager);
注意
class I extends User {
}
// 相当于
class I extends User {
constructor (...arg){
super(...arg);
}
}
闻鸡起舞成就拼搏劲旅师,天道酬勤再现辉煌王者风。
网友评论