1.判断基本数据类型typeof 判断对象的类型 Object.prototype.toString.call()
//使用 typeof bar === "object" 判断 bar 是不是一个对象弊端?
//使用 typeof 的判断Object弊端是显而易见的(这种弊端同使用 instanceof):
let obj = {};
let arr = [];
console.log(typeof obj === 'object'); //true
console.log(typeof arr === 'object'); //true
console.log(typeof null === 'object'); //true
//从上面的输出结果可知,typeof bar === "object" 并不能准确判断 bar 就是一个 Object。可以通过 Object.prototype.toString.call(bar) === "[object Object]" 来避免这种弊端:
let obj = {};
let arr = [];
console.log(Object.prototype.toString.call(obj)); //[object Object]
console.log(Object.prototype.toString.call(arr)); //[object Array]
console.log(Object.prototype.toString.call(null)); //[object Null]
2.即时执行函数 IIFE
(function(){
var a = b = 3;
})();
console.log(b); //3 全局变量
console.log(a); //undefined
for(var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
//上面的输出并不是你以为的0,1,2,3,4,而输出的全部是5,这时 IIFE 就能有用了:
for(var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000);
})(i)
}
3
.对于 return 、break、continue 等语句,如果后面紧跟换行,后面一定要加分号;
function foo1()
{
return {
bar: "hello"
};
}
function foo2()
{
return
{
bar: "hello"
};
}
console.log(foo1());
console.log(foo2());//undefined
4.闭包能够访问外部作用域的变量和参数
(function(x) {
return (function(y) {
console.log(x);
})(2)
})(1); //1
var hero = {
_name: 'John Doe',
getSecretIdentity: function (){
return this._name;
}
};
var stoleSecretIdentity = hero.getSecretIdentity;
console.log(stoleSecretIdentity);
console.log(hero.getSecretIdentity());
// 将 getSecretIdentity 赋给 stoleSecretIdentity,等价于定义了 stoleSecretIdentity 函数:
// var stoleSecretIdentity = function (){
// return this._name;
// }
// stoleSecretIdentity
// 的上下文是全局环境,所以第一个输出 undefined。若要输出 John Doe,则要通过 call 、apply 和 bind 等方式改变 stoleSecretIdentity 的this 指向(hero)。
// 第二个是调用对象的方法,输出 John Doe。