原型链对象扩展内置对象方法
//给数组添加一个add方法
console.log( Array.prototype)
Array.prototype.add = function () {
var num = 0;
for (let i = 0; i < this.length; i++) {
num += this[i]
}
return num
}
var arr = [1,3,5,7]
console.log(arr.add())
//给字符串添加一个sehi方法
String.prototype.sehi=function(){
console.log(this)
console.log(this+'哈哈哈')
}
var str = '妹大爷'
str.sehi()
构造函数生成一个全局随机数方法
(function fun(window) {
function Ran() {
}
Ran.prototype.random = function () {
return Math.floor(Math.random() * 10);
}
window.ras = new Ran()
// console.log(window.random())
})(window)
console.log( window.ras.random())
call
// call改变函数内部的this指向并执行函数,后面可以正常带参数
// 主要作用可以实现继承
function fn(a, b) {
console.log(this)
}
var obj = {
name: '张三晓'
}
fn()
fn.call(obj, 1, 3)
**继承实例**
function Father(name,age){
// 将父构造函数里面的属性继承到子类里面
this.name = name
this.age = age
console.log(this.name,this.age)
}
function Son(name,age){
// 调用父构造函数时将父的this指向子构造函数,这样就可以使用子函数里面的值了
Father.call(this,name,age)
}
var son = new Son('张学友','60')
console.log(son)
apple
//和call差不多,apple只能传一个数组作为参数
function fn(a, b) {
console.log(this)
console.log(a + b)
}
var obj = {
name: '张三晓'
}
// null表示不改变指向,
fn.apply(null,[1,3,5,7,9])
```js
**bind**
//不会调用函数
function fn(a, b) {
console.log(this)
console.log(a + b)
}
var obj = {
name: '张三晓'
}
var f = fn.bind(obj, 1, 2)
// 返回一个新的函数,其他地方和call一样
f()
**闭包**
> 作用:在函数执行完之后,他内部的局部变量依旧存在内存中(延长了局部变量的生命周期),让函数外部可以操作(读写)到函数内部的变量、函数;
> 闭包是嵌套的内部函数(包含被引用‘函数、变量’的对象),存在于函数中
> 闭包不清除容易造成内存泄漏,使用完最好主动清除**(fun1=null)**
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190912164637782.png)
```js
var car = (function(){
var num = 10
var us = 0
return {
price:function(e){
if(e>3){
return num+(e-3)*5
}else{
return num
}
},
}
})()
let all = car.price(10)
console.log(all)
//清除闭包
car= null
内存泄漏和溢出
内存泄漏达到内存最大值时就出现溢出
常见的内存泄漏
- 意外或无用的全局变量
- setInterval函数没有清除
- 闭包没有清除