- console.log(this === window);
- var obj = function(p){
- this.p = p;
- }
- obj.prototype.getP = function(){
- return this.p;
- }
- var o = new obj("Hello World!");
- console.log(o.p);
- >>> Hello World!
- console.log(o.getP());
- >>> Hello World!
- var obj = {
- f1:function(){
- console.log(this);
- var f2 = function(){
- console.log(this);
- }();
- }
- }
- obj.f1();
- >>> Object
- Window
上面代码包含两层this,结果运行后,第一层指向该对象,第二层指向全局对象。
如何修改?改用一个指向外层this的变量_that
- var obj = {
- f1:function(){
- console.log(this);
- var _that = this;
- var f2 = function(){
- console.log(_that);
- }();
- }
- }
- obj.f1();
- >>> Object
- Object
- var obj = {
- v:'hello',
- p:['a1','a2'],
- f: function f(){
- this.p.forEach(function(item){
- console.log(this.v + ' ' + item);
- });
- }
- }
- obj.f();
- >>> undefined a1
- undefined a2
出现undefined的原因是forEach方法的回调函数中的this,其实是指向window对象,因此取不到obj.v的值
解决方法一:使用中间变量
- var obj = {
- v:'hello',
- p:['a1','a2'],
- var _that = this;
- f:function f(){
- this.p.forEach(function(item){
- console.log(_that.v + ' ' + item);
- });
- }
- }
- obj.f();
- >>> hello a1
- hello a2
解决方法二:将this当作foreach方法的第二个参数
- var obj = {
- v:'hello',
- p:['a1','a2'],
- f:function f(){
- this.p.forEach(function(item){
- console.log(this.v + ' ' + item);
- },this);
- }
- }
来源: http://www.qdfuns.com/notes/46099/e7ce3221815d8af24114738689c4495e.html