Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

使用对象的方法,为什么控制台结果里,多了一个undifined?

Q1为什么控制台,最后输出了两个undifined?
clipboard.png

var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: 'Hello'
  }
};

var hello = a.b.m;
hello()

Q2感觉这里也是多了一个undifined
clipboard.png

//代码
var a = {
  b: {
    m: function() {
      console.log(this.p);
    },
    p: 'Hello'
  }
};
var hello = a.b;
hello.m();

补充:
问题来源:
阮一峰的JS标准里this关键字
上面代码就是链接里,2.(3)对象的方法 最后一段


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

自动自答,总结前人的帮助:

Q1
第一个undefined,因为hello指向了一个方法,可以看做functionName,所以this就是window
this.p; //window.p//首先声明一个window.p,未赋值,值是undifined

关键是多了一个undifined!
第二个undefined,前面有个箭头,
在 m 函数里加一个 return 'test',//"test"
所以,这个箭头可以看做return后面的值,这里m函数没有return,没有返回值就是undifined
总结:前面这个箭头,是控制台独有的,命令行调试时没有
控制台先是执行函数,然后是,输出函数的执行结果(比如再用来 给别的赋值)

Q2
第一个undefined,因为hello指向了一个对象,可以看做b,所以this.p; //b.p


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...