关于this的类型 - pod4g/tool GitHub Wiki
this
只能是引用类型不能是基本类型
1. 如果显示地通过bind
,call
,apply
绑定的this
是基本类型的话,js引擎会自动包装成相应的对象类型(当然,null和undefined除外)
function t(){
console.log(this.length);
console.log(this);
}
var nt = t.bind('abc');
nt();// 3
// String {0: "a", 1: "b", 2: "c", length: 3, [PrimitiveValue](/pod4g/tool/wiki/PrimitiveValue): "abc"}
t.call("defg"); // 4
// String {0: "d", 1: "e", 2: "f", 3: "g",length: 4, [PrimitiveValue](/pod4g/tool/wiki/PrimitiveValue): "defg"}
2. 绑定null和undefined
如果绑定null
和undefined
那么会默认指向全局对象
function t() {
console.log(this)
}
var nt = t.bind(null)
nt() // window
var nt2 = t.bind(void 0)
nt2() // window
在严格模式下,绑定的是什么,就是什么(故如果在函数中使用this.属性
在严格模式下会引起TypeError: Cannot read property '属性' of null)
'use strict'
function t() {
console.log(this)
}
var nt = t.bind(null)
nt() // null
var nt2 = t.bind(void 0)
nt2() // undefined
3. 方括号访问属性的转换问题
如果通过 obj[object] 来调用一个成员的话,js引擎会调用 ToString(object),把object指向的对象转成一个字符串
var str = new String("aabbcc");
var aabbcc = "我是aabbcc";
// 会把str对象转成字符串。所以可以正确地得到结果
window[str]; // 我是aabbcc