JavaScript中的this

2017-10-10  本文已影响0人  JYOKETSU3

例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
上一篇下一篇

猜你喜欢

热点阅读