javascript命名空间及对象枚举的理解

命名空间的意思是管理变量,防止污染全局,适用于模块化开发

以前的做法(现在不在使用)

var obj = {
  department1: {
    lyj: '',
    ...
  },
  department2: {
    ccc: ''
  },
  ...
}

现在新的方法(闭包)

var initDeng = (function() {
  var name = 'abc'
  function callName() {
    console.log(name)
  }
  return function() {
    callName()
  }
}())
var initZhang = (function() {
  var name = 'def'
  function callName() {
    console.log(name)
  }
  return function() {
    callName()
  }
}())
initDeng() //abc
initZhang() //def
//里面的name互不影响

看下面代码(模仿Jquery链式反应)

var deng = {
  smoke: function() {
    console.log('smoke')
    return this
  },
  drink: function() {
    console.log('drink')
    return this
  },
  perm: function() {
    console.log('perm')
    return this
  }
}
deng.smoke().drink().perm()
//模仿jQuery的链式调用,原理是在方法内return this

对象枚举 (for in

var obj = {
  name: 'lyj',
  sex: '男',
  age: 18
}
for(var key in obj) {
  console.log(key)
  console.log(obj[key])
}

再看一下例子

var obj = {
  name: 'lyj',
  sex: '男',
  age: 18,
  __proto__: {
    lastName: 'li'
  }
}
Object.prototype.firstNmae = 'yingjie'
for(var key in obj) {
  // console.log(key)
  // console.log(obj[key])  //会打印出原型链上的属性和值

  if(obj.hasOwnProperty(key)) {  //过滤是否是自己身上的属性
    console.log(key)      //不会打印出原型链上的属性和值
    console.log(obj[key])   } }
//最好for in 和 hasOwnProperty一起使用,为了过滤出自己身上的属性

in 操作符(基本不常用), 判断是否是对象的属性

var obj = {
  name: 'lyj',
  sex: '男',
  age: 18,
  __proto__: {
    lastName: 'li'
  }
}
Object.prototype.firstNmae = 'yingjie'
console.log('name' in obj)      //true
console.log('abc' in obj)       //false
console.log('lastName' in obj)  //true
console.log('firstNmae' in obj) //true

instanceof
a instanceof A 判断对象a的原型链上 是否有 A的原型(A.prototype)

function Person() {

}
var person = new Person()
console.log(person instanceof Person)  //true
console.log(person instanceof Object)  //true
console.log([] instanceof Array)   //true
console.log([] instanceof Object)  //true
console.log({} instanceof Object)  //true
console.log({} instanceof Array)   //false

判断输数值还是对象三种方法

var a = []  
var b = {}

//1. constructor
console.log(a.constructor)  //Array
console.log(b.constructor)  //Object

//2. instanceof
console.log(a instanceof Array)  //true
console.log(b instanceof Array)  //false

//3. toString
console.log(a.toString())  //
console.log(b.toString())  //[object Object]

//原理
Object.prototype.toString = function() {
  // 识别this
  // 返回结果
}

再看下面例子区别基本类型和引用类型

console.log(Object.prototype.toString.call()) //[object Undefined]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(123)) //[object Number]
console.log(Object.prototype.toString.call(true)) //[object Boolean]

call的参数1改变this,返回对应this类型toString方法

end !!!

原文地址:https://www.cnblogs.com/lyjfight/p/13815707.html