ES6中的class 与prototype
2024-09-05 19:29:37
一、定义构造函数
在以前的js中,生成一个对象实例,需要先定义构造函数,然后通过prototype 的方式来添加方法,在生成实例:
function Person(){
this.name = "测试";
this.age = 26;
} Person.prototype.getName = function(){
console.log("name:" + this.name) } var p = new Person()
然而系现在的ES6
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
} var p = new Person("luoqiang",26)
在ES5中原本的构造函数被constructor 替代,本来需要定义在prototype上面的,方法直接定义在class里面即可。
ES6中的类的数据类型就是函数,类本身指向构造函数,使用的时候也需要new命令。
类中所有的方法都定义在类的prototype属性上面。
class B {}
let b = new B(); b.constructor === B.prototype.constructor // true
二、Class 的静态方法
ES6 中类有静态方法,即一个方法前加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用。
class Food {
static classMethod() {
return 'hello'
}
} Food.classMethod() // "hello" var poo = new Food();
poo.classMethod() // TypeError: poo.classMethod is not a function
通过类直接调用,输出的是hello,实例化以后不能调用。
PS:
在react、 RN中,this.state ={} 这种写法是在constructor 里面定义实例属性。
class ReactCounter extends React.Component {
state;
constructor(props){
super(props);
this.state = {
count:0
}
}
}
super(props)是继承父类的props 属性,state是在子类中定义实例属性。
三、class 继承
以前的继承方式:
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.getName = function(){
console.log("name:" + this.name);
} function Stu(stu_class,name,age){
Person.call(this,name,age);
this.stu_class=stu_class;
} Stu.prototype=new Person;
Stu.prototype.constructors=Stu;
Stu.prototype.getClass=function(){
console.log("班级:" + this.stu_class)
} // 得到一个学员信息对象 var s= new Stu()
console.log(s)
ES6的继承:
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
getName(){
return this.name;
}
} class Student extends Person{
constructor(stu_class,name,age){
//需注意如果一个子类继承父类,必须调用super,才能使用constructor,使用this
super(name,age)
}
getClass(){ console.log("班级:"+this.stu_class)
}
} var p=new Person("luoqiang",26)
console.log(p)
注意点:
Class 定义方法是不能使用箭头函数
Class 也可以使用表达式方式声明
参考:https://blog.csdn.net/luoqiang0831/article/details/79641133
最新文章
- Java中ProcessBuilder应用实例
- Nginx系列一:信号与配置
- java——多线程——内部类共享同一个外部类对象的成员变量
- Nancy 学习-身份认证(Basic Authentication) 继续跨平台
- 屌丝逆袭--Asp.net快速入门学习教程 第1晚
- Jfinal验证码功能
- CPU大小端判断
- Linq 用法笔记
- (int)、(int&;)和(int*)的区别(转)
- Contest20140906 ProblemA dp+线段树优化
- android 网络状态判断【转】
- WEB 端批量移动设备管理控制工具 STF 的环境搭建和运行
- 开发H5基本知识摘要
- Saltstack基础
- TCP的核心系列 — 重传队列的更新和时延的采样(一)
- BZOJ4552 HEOI2016/TJOI2016排序(线段树合并+线段树分裂)
- 【webpack】中file-loader和url-loader使用方法
- C# .Net List<;T>;中Remove()、RemoveAt()、RemoveRange()、RemoveAll()的区别,List<;T>;删除汇总
- 42_redux_counter应用_redux异步版本
- php插入日志到数据库,对象转json
热门文章
- Linux下Reids的安装和使用
- Could not open lock file/var/lib/dpkg/lock
- Linux学习之十三-vi和vim编辑器及其快捷键
- curses.h头文件不存在解决办法
- 135 - ZOJ Monthly, August 2014
- int a; int* a; int** a; int (*a)[]; int (*a)(int)
- Linux下MySQL定时按日期备份数据
- phpQuery—基于jQuery的PHP实现(转)
- HDU 3461 Code Lock(并查集的应用+高速幂)
- PLSQL怎样导出oracle表结构