前端高级编程含es6-创建类和实例对象-类中添加方法-类的继承-子类扩展方法
Posted 勇敢*牛牛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端高级编程含es6-创建类和实例对象-类中添加方法-类的继承-子类扩展方法相关的知识,希望对你有一定的参考价值。
【前端高级编程含es6】-创建类和实例对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6类</title>
</head>
<body>
</body>
<script>
//1.创建一个类
class Star
constructor(unname,age)
this.unname = unname;
this.age = age;
//2.利用类创建对象new
var n = new Star('勇敢牛牛',4);
console.log(n.unname)
console.log(n.age)
</script>
</html>
- 通过calss关键字创建类,类名的首字母习惯性的大写
- 类里面有一个constructer函数,可以接受传递过来的参数,同时返回实例对象
- constructer函数只要new生成实例时就会自动调用,如果我们不写这个函数,也会自动生成这个函数。
- 生成实例不能省略new
- 注意语法“创建类:类名后面没有小括号,生成实例:后面加小括号,构造函数不需要写funtion”
类中添加方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6类</title>
</head>
<body>
</body>
<script>
//1.创建一个类
class Star
constructor(unname,age)
this.unname = unname;
this.age = age;
sing(song)
console.log('我唱这首唱歌',song)
//2.利用类创建对象new
var n = new Star('勇敢牛牛',4);
console.log(n.unname)
console.log(n.age)
n.sing('一giao我哩giao')
</script>
</html>
- 类中方法不需要写funtion
- 多个函数中不需要写逗号隔开
类的继承
子类继承父类的一些属性和方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6类</title>
</head>
<body>
</body>
<script>
//1.创建一个类
class Father
constructor(x,y)
this.x = parseInt(x);
this.y = parseInt(y);
money()
console.log(100)
sum()
console.log(this.x);
console.log(this.y);
console.log(this.x + this.y);
class Son extends Father
//super 关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,和普通函数
constructor(x,y)
super(x,y);//调用父类中的构造函数
//2.利用类创建对象new
var n = new Son(1,2);
n.sum();
</script>
</html>
- super 关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,和普通函数
- 继承中存在就近原则
调用父类的普通函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6类</title>
</head>
<body>
</body>
<script>
//1.创建一个类
class Father
constructor(x,y)
this.x = parseInt(x);
this.y = parseInt(y);
money()
return 100;
sum()
console.log(this.x);
console.log(this.y);
console.log(this.x + this.y);
class Son extends Father
//super 关键字用于访问和调用对象父类上的函数,可以调用父类的构造函数,和普通函数
constructor(x,y)
super(x,y);//调用父类中的构造函数
money()
console.log(super.money()+"是父亲的钱")
//2.利用类创建对象new
var n = new Son(1,2);
n.sum();
n.money();
</script>
</html>
以上是关于前端高级编程含es6-创建类和实例对象-类中添加方法-类的继承-子类扩展方法的主要内容,如果未能解决你的问题,请参考以下文章