严格模式

'use strict';
 
eval(string); // eval 函数:执行 js 代码,严格模式下有单独作用域

JSON 对象

jsonString = JSON.stringify(obj);
jsonObj = JSON.parse(string);

Object 扩展

ES5 给 Object 扩展了一些静态方法,常用的有 2 个:

Object.defineProperties

Object.defineProperties(object, descriptors)
  • 作用:为指定对象定义扩展多个属性
  • descriptors(对属性进行描述):
    • get:用来获取当前属性值的回调函数
    • set:修改当前属性值得触发的回调函数,并且接收参数
    • value:指定值
    • writable:标识当前属性值是否是可修改的,默认为 false
    • configurable:标识当前属性值是否可以被删除,默认为 false
    • enumerable:标识当前属性值是否能用 for in 枚举,默认为 false

setter & getter:

var obj = { firstName: 'kobe', lastName: 'bryant' };
Object.defineProperties(obj, {
  fullName: {
    get: function () {
      return this.firstName + ' ' + this.lastName;
    },
    set: function (data) {
      var names = data.split(' ');
      this.firstName = names[0];
      this.lastName = names[1];
    }
  }
})
 
console.log(obj.fullName); // kobe bryant
obj.fullName = 'tim duncan';
console.log(obj.fullName); // tim duncan
Object
  firstName: "tim"
  lastName: "duncan"
  fullName: (...) // "tim duncan" 惰性:调用get()
  get fullName: ƒ ()
  set fullName: ƒ (data)
  __proto__: Object

Object.create

Object.create(prototype, [descriptors])
  • 作用:以指定的对象为原型创建新的对象
  • 为新的对象指定新的属性,并对属性进行描述

范例:

var obj = { name: 'zhangsan', age: 18 };
var obj1 = Object.create(obj, {
  sex: {
    value: '男',
    writable: true,
    configurable: true,
    enumerable: true
  }
};
 
console.log(obj1);
Object
  sex: "男"
  __proto__:
    age: 18
    name: "zhangsan"
    __proto__: Object

Array 扩展

Array.prototype.indexOf(value)
// 返回 index:根据 value 找 index,从前往后
  
Array.prototype.lastIndexOf(value)
// 返回 index:根据 value 找 index,从后往前
  
Array.prototype.forEach(function(item, index){})
// 遍历数组
  
Array.prototype.map(function(item, index){})
// 映射:一对一
// 遍历数组,返回一个新数组
  
Array.prototype.filter(function(item, index){})
// 过滤
// 遍历数组,过滤出的新的子数组并返回(过滤条件:return true)
  items
    .filter(item => loc == cur_loc)
    .filter(item => item.price >= 60 && item.price <= 100);
    
Array.prototype.reduce(function(tmp, item, index){})
// 减少:多对一
// 遍历数组,不改变原数组,返回一个运算值
  let arr = [1, 2, 3, 4];
  let result = arr.reduce((tmp, item, index) => {
    console.log(`第${index}次,${tmp} + ${item}`);
    return tmp + item;
  })
  console.log(result); // 10
  /*
   * 第1次,1 + 2
   * 第2次,3 + 3
   * 第3次,6 + 4
  */

Function 扩展

Function.prototype.call(obj)
// 将函数内的 this 指向为 obj,并立即调用
 
Function.prototype.apply(obj)
// 将函数内的 this 指向为 obj,并立即调用
 
Function.prototype.band(obj)
// 将函数内的 this 指向为 obj,并返回函数
  • call 和 apply 区别,函数传参时:

    • call:从第二位依次传入
    • apply:第二位传入一个数组,数组中包含参数
  • bind 和 call、apply 区别:

    • bind:将函数返回
    • call、apply:立即调用函数
    • 函数传参时:bind 同 call

闭包

  • GC:垃圾回收机制
  • 闭包:防止垃圾回收 —— 留着别删
  • 实现:
    1. 底层:栈
    2. 高层:函数当作对象处理
window.onload = function() {
  var btns = document.getElementsByTagName('button');
 
  for (var i = 0; i < btns.length; i++) {
    (function(i) {
      btns[i].onclick = function() {
        console.log(i);
      }
    })(i);
  }
}