1.

var User = {
  count: 1,
  getCount: function () {
    return this.count;
  } };
console.log(User.getCount()); // 1
var func = User.getCount;
console.log(func()); // undefined

执行过程:

console.log(User.getCount());     // 1

getCount函数被User对象调用,所以this指向的是User。

console.log(func());              // undefined

func变量接收的是一个函数体:

function () {
  return this.count;  
}

所以, func()执行的时候, this指的是window, 而window中没有count这个属性。 所以,返回的是undefined。

 

2.

var name = "The Window";

var object = {
  name : "My Object",

  getNameFunc: function () {
    return function () {
      return this.name;
    };
  } };
alert(object.getNameFunc()()); //"The Window" (在非严格模式下)

执行过程:

以上代码先创建了一个全局变量 name, 又创建了一个包含 name 属性的对象。

 

相关文章:

  • 2021-08-03
  • 2022-03-08
  • 2022-12-23
  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-30
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-22
相关资源
相似解决方案