- js语言传统方法是通过构造函数,定义并生成新对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function Fn(x, y) {
this.x = x
this.y = y
}
Fn.prototype.toTo = function () {
console.log(this.x + this.y)
}
fn = new Fn(1, 2)
console.log(fn)
fn.toTo()
</script>
</body>
</html>
- 使用es6中的class类定义生成新对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
class Fn {
constructor(x, y) {
this.x = x
this.y = y
}
toTo() {
console.log(this.x + this.y)
}
}
console.log(Fn)
var fn = new Fn(1, 2)
console.log(fn)
fn.toTo()
</script>
</body>
</html>
3.es5实现继承(构造函数和原型链组合继承)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function Parent(name) {
this.name = name
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(name) {
Parent.call(this, name)
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
var child = new Child('haha')
child.getName()
console.log(child.name)
</script>
</body>
</html>
4.es6实现继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
class Parent {
constructor(x, y) {
this.x = x
this.y = y
}
say() {
console.log(this.x + this.y)
}
}
class Child extends Parent {
constructor(x, y, z) {
super(x, y) // super的含义,父类的调用,但是返回的是子类的实例
this.z = z
}
call() {
console.log(this.x + this.y + this.z)
}
}
const child = new Child(2, 3, 4)
console.log(child, 'child')
child.call()
child.say()
</script>
</body>
</html>
5.super关键字
第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。