JS高级基础

## 数据类型的分类和判断

* 基本(值)类型

* Number ----- 任意数值 -------- typeof

* String ----- 任意字符串 ------ typeof

* Boolean ---- true/false ----- typeof

* undefined --- undefined ----- typeof/===

* null -------- null ---------- ===

* 对象(引用)类型

* Object ----- typeof/instanceof

* Array ------ instanceof

* Function ---- typeof

对象

对象的组成

  • 属性: 
  • 方法 : 特别的属性

访问方式

  • .属性名 : 有时不通用
  • ['属性名']: 通用但是麻烦
  var p = {
    name: 'Tom',
    age: 12,
    setName: function (name) {
      this.name = name
    },
    setAge: function (age) {
      this.age = age
    }
  }
  p.setName('Bob')
  p['setAge'](23)
  console.log(p.name, p['age'])

问题: 什么时候必须使用['属性名']的方式?

1. 属性名包含特殊字符: - 空格

2. 属性名不确定

  var p = {}
  //1. 给p对象添加一个属性: content type: text/json
  // p.content-type = 'text/json' //不能用
  p['content-type'] = 'text/json'
  console.log(p['content-type'])

  //2. 属性名不确定
  var propName = 'myAge'
  var value = 18
  // p.propName = value //不能用
  p[propName] = value
  console.log(p[propName])

函数

  • 只有函数是可以执行的, 其它类型的数据不能执行

  • 如何调用(执行)函数?

  • * test(): 直接调用  this = window
  • * obj.test(): 通过对象调用 this = obj
  • * new test(): new调用    this 是新创建的对象
  • * test.call/apply(obj): 临时让test成为obj的方法进行调用  this = obj
  var obj = {}
  function test2 () {
    this.xxx = 'atguigu'
  }
  // obj.test2()  不能直接, 根本就没有
  test2.call(obj) // obj.test2()   // 可以让一个函数成为指定任意对象的方法进行调用  //给obj 添加了 xxx属性
  console.log(obj.xxx) 
  • * 函数也是对象
  • * instanceof Object===true
  • * 函数有属性: prototype
  • * 函数有方法: call()/apply()
  • * 可以添加新的属性/方法
  • * 函数的3种不同角色
  • * 一般函数 : 直接调用
  • * 构造函数 : 通过new调用
  • * 对象 : 通过.调用内部的属性/方法
  • * 函数中的this
  • 任何函数本质上都是通过某个对象来调用的,如果没有直接指定就是window
  • 所有函数内部都有一个变量this

  • 它的值是调用函数的当前对象

  • * 显式指定谁: obj.xxx()
  • * 通过call/apply指定谁调用: xxx.call(obj)
  • * 不指定谁调用: xxx() : window
  • * 回调函数: 看背后是通过谁来调用的: window/其它
  • * 匿名函数自调用:
  • (function(w, obj){//实现代码}) (window, obj)
function Person(color) {
    console.log(this)
    this.color = color;
    this.getColor = function () {
      console.log(this)
      return this.color;
    };
    this.setColor = function (color) {
      console.log(this)
      this.color = color;
    };
  }

  Person("red"); //this是谁? window

  var p = new Person("yello"); //this是谁? p

  p.getColor(); //this是谁? p

  var obj = {};
  p.setColor.call(obj, "black"); //this是谁? obj

  var test = p.setColor;
  test(); //this是谁? window

  function fun1() {
    function fun2() {
      console.log(this);
    }

    fun2(); //this是谁? window
  }
  fun1();

IIFE

作用 隐藏实现不会污染外部(全局)命名空间, 用它来编码js模块.

 (function () { //匿名函数自调用
    var a = 3
    console.log(a + 3)
  })()
  var a = 4
  console.log(a)

(function () {
    var a = 1
    function test () {
      console.log(++a)
    }
    window.$ = function () { // 向外暴露一个全局函数
      return {
        test: test
      }
    }
  })()   //初始化函数对象的属性

  $().test() // 1. $是一个函数 2. $执行后返回的是一个对象  $() ->> test 函数对象   test() 是调用test  组合起来就是 $().test()

猜你喜欢

转载自blog.csdn.net/qq_38003454/article/details/83893244