this
this
window
this === window
true
var myVar = 'my Day';
undefined
myVar
"my Day"
this.myVar
"my Day"
window.myVar
"my Day"
var a = {}
undefined
a.name = 'suqing'
"suqing"
var a = { name: 'suqing', context: this }
undefined
a.context
a.context === window
true
function foo(){ // something }
undefined
foo()
undefined
foo.trueExpertise = 'beginner';
"beginner"
foo.trueExpertise
"beginner"
foo.this
undefined
function whatIsThis(){ return this; }
undefined
whatIsThis()
(function(){ return this; })()
(function(){ 'use strict'; return this; })()
undefined
(function(self){ 'use strict'; return this; })(this)
undefined
(function(self){ 'use strict'; return self; })(this)
对象的this
var a = { name: 'suqing', getContext: function(){ return this; } }
undefined
a.getContext()
var d = { name: 'yefeng' }
undefined
d.getContext = a.getContext
function (){ return this; }
d.getContext()
var foo = a.getContext
undefined
foo
function (){ return this; }
foo()
a.getContext()
d.getContext()
foo()
var foo = a.getContext
undefined
foo()
构造器
function Friend() { this.area = area; this.favLan = favLan; this.context = this; }
undefined
function Friend(area, favLan) { this.area = area; this.favLan = favLan; this.context = this; }
undefined
var frnd1 = new Friend('client','js')
undefined
frnd1.context
var frnd2 = new Friend('server','java')
undefined
frnd2.context
Friend('server', 'java')
undefined
prototype链
var dad = { fatherName: 'Dad' }
undefined
var child = Object.create(dad)
undefined
child.fatherName
"Dad"
child.whoIsYourDad = function(){ return this.fatherName; }
function (){ return this.fatherName; }
child.whoIsYourDad()
"Dad"
参数this
function getMenu(){ return this; }
undefined
var devMenu = { menu: 'pizza' }
undefined
var forDev = getMenu.bind(devMenu)
undefined
forDev()
Object {menu: "pizza"}
var hrMenu = { menu: 'salad' }
undefined
var forHR = getMenu.bind(hrMenu)
undefined
forHR()
Object {menu: "salad"}
getMenu.call
function call() { [native code] }
getMenu.apply
function apply() { [native code] }
getMenu.apply(hrMenu)
Object {menu: "salad"}
getMenu.call(hrMenu)
Object {menu: "salad"}
setTimeout
var a = { getContext: function(){ setTimeout( function(){ console.log(this); }, 10) } }
undefined
a.getContext()
undefined
var a = { getContext: function(){ setTimeout( function(){ console.log(this); }, 4000) } }
undefined
a.getContext()
undefined
DOM event handler
document.getElementById('s_rp_words').addEventListener('click', function(){ console.log(this); })
undefined