Skip to content

Instantly share code, notes, and snippets.

@Gerhut
Created May 27, 2014 04:51
Show Gist options
  • Select an option

  • Save Gerhut/ef9308d3a778c8ba2c8c to your computer and use it in GitHub Desktop.

Select an option

Save Gerhut/ef9308d3a778c8ba2c8c to your computer and use it in GitHub Desktop.
var x = 10;
foo = {
x: 20,
bar: function () {
var x = 30;
return this.x;
}
}
/*
bar函数由foo调用,所以this是foo,foo.x是20
*/
console.log(foo.bar()); // 20
/*
和前一个一样,bar函数由foo调用,所以this是foo,foo.x是20
*/
console.log((foo.bar)()); // 20
/*
一个=号是赋值运算符,赋值运算符的返回值是运算符右边的值,这里就是bar函数本身。
所以这里直接调用了bar函数,直接调用函数时this是全局,全局的x是10。
*/
console.log((foo.bar = foo.bar)()); // 10
/*
和前一个一样,逗号运算符的返回值是逗号右边的内容,这里就是bar函数本身。
所以这里直接调用了bar函数,直接调用函数时this是全局,全局的x是10。
*/
console.log((foo.bar, foo.bar)()); // 10
/*
总结:当拥有调用源的函数经过至少一次运算之后再执行,会丢掉它的调用源。
*/
@kabaskimy

Copy link
Copy Markdown

第二个没说清楚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment