JavaScript中的this

  • 自运行函数其实是window对象调用它!函数分普通函数和构造函数,普通函数的this指向window,构造函数的this指向它本身,谁调用它this就指向谁!
  • 函数定义的方式(通过函数声明、函数表达式、new Function)与this的取值无关,有没有闭包也与this无关!

例1

var price = 100;
var Book = function(){
  this.price = 200;
  return function(){
    console.log(this===window); // true (执行book()时打印)
    return this.price;
  }
};

var book = new Book();
console.log(book); // function(){...} (内容为return的函数体内容)
console.log(book()); // 100

例2

var Book = (function(){
  var name="test";
  console.log(this===window); // true (自执行函数执行时打印)
  return function(){
    this.price=200;
    this._name=name;
    console.log(this); // Object{_name: "test",price: 200} (new运算符生成book对象时打印)
  }
})();

var book = new Book();
console.log(Book instanceof Function); // true (函数体为return的函数内容)
console.log(book); // Object{_name: "test",price: 200} (new运算符生成book对象时打印)
console.log(book.price); // 200
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容