组合继承
<script>
// 组合继承:属性继承(call)、方法继承(原型继承)
var Person = function (name, age) {
this.name = name
this.age = age
}
Person.prototype.sayHi = function () {
console.log('hi')
}
var Student = function (name, age, score) {
// 属性继承使用call方法
Person.call(this, name, age)
this.score = score
}
// 方法继承使用原型
Student.prototype = new Person()
// 上一行代码改变了Student.prototype.constructor为Person,所以我们要重新给Student.prototype.constructor赋值Student
Student.prototype.constructor = Student
var st = new Student('oy', 20, 90)
console.log(st.name + ' ' + st.age + ' ' + st.score)
console.log(Student.prototype.constructor)
st.sayHi()
var p = new Person('zm', 18)
console.log(p.constructor)
</script>
函数
定义函数
- 函数声明
- 函数表达式
- 通过构造方法定义函数
<script>
// 1、函数定义存在函数提升
fun2() //打印fn2
function fun2 () {
console.log('fn2')
}
// 2、函数表达式不存在函数提升
// f() //提示f不是一个函数
// var f = function fun1 () {
// console.log('fn1')
// }
// f() // 打印fn1
// 3、通过构造方法定义函数
console.log(fun3(2, 3)) // 报错,提示fun3不是函数
var fun3 = new Function('a', 'b', 'var a = 1; console.log(a + b)')
console.log(fun3(2, 3)) // 打印4
</script>
函数中this的指向
call、apply、bind
- call方法用于改变函数内部的this指向。call方法有多个参数:第一个参数:this指向,后面的参数:传入的参数列表
- apply方法和call方法的区别是:apply方法有两个参数:第一个参数:this指向,第二个参数是传入参数组成的数组
- bind方法传参和call方法一致。但返回值是一个指定了this的函数,且bind方法不能调用
call方法的应用
- 构造函数属性的继承
var Person = function (name, age) {
this.name = name
this.age = age
}
var Student = function (name, age, score) {
// 属性继承使用call方法
Person.call(this, name, age)
this.score = score
}
- 构造函数扩展原型对象方法
var o = {
'0': 1,
'1': 2,
'2': 3,
length: 3
}
Array.prototype.push.call(o, 4)
console.log(o)
apply方法的应用
// 数组调用js的内置函数
var arr = [1, 2, 3]
console.log(Math.max.apply(Math, arr))
bind方法的应用
// 3、更改定时器、延时器的this
var o = {
'name': 'zm',
'sayHi': function () {
setInterval (function() {
console.log('hi')
console.log(this) //打印当前对象
}.bind(this), 1000)}
}
//o.sayHi()
// 更改事件函数的this
document.onclick = function () {
console.log(this) // 点击页面,打印o对象
}.bind(o)
函数中的其他成员
- arguments:实参集合,是一个类数组对象
- arguments.callee:函数本身
- fn.caller:函数的调用者,如果函数处于全局作用域,则为null
- fn.name:函数的名称
- fn.length:函数的形参个数
高阶函数
- 函数可以作为参数
// 1.函数作为另一个函数的参数
// 定义一个函数,吃饭的函数,吃完饭之后,可以做其他的事情,看电影、聊天、看书
function eat(fn) {
console.log("吃晚饭");
// 接下来的要做的事情是不固定的
fn();
}
eat(function () {
console.log("看电影");
});
- 函数也可以作为返回值
// 2.函数作为一个函数的返回值
// 需求:通过同一段代码实现以下效果
// 输出 100 + m
function outer(n) {
return function inner(m) {
console.log(m + n);
}
}
// 在外部执行 inner 函数
// 100 + m
var fun = outer(100);
fun(3);
函数闭包
什么是闭包
- 闭包可以让你在函数外访问函数内部的作用域。在js中,每创建一个函数,闭包就会在函数创建的同时被创建出来
- 闭包中包含函数所能访问的作用域环境和函数自己,将他们形成一个密闭的环境,这就是闭包。只要函数调用,就会回到密闭环境进行执行
闭包的用途
可以在函数外访问函数的内部成员
让给你函数内部成员始终存活在内存中