javascript 中 this 的指向

来源:互联网 发布:javascript选项卡代码 编辑:程序博客网 时间:2024/05/16 01:16

在函数中 this 指向 window

(function whatThis() {  console.log(this);})()
输出结果:
Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}


在方法中 this 指向 调用方法的对象

var object = {  getThis: function() {    console.log(this);  }}object.getThis();
输出结果:

  1. Object {}
    1. getThis:()
      1. arguments:null
      2. caller:null
      3. length:0
      4. name:"getThis"
      5. prototype:Object
      6. __proto__:()
      7. <function scope>
    2. __proto__:Object

在构造函数的实例中,this 指向 new 出的实例

var GetThis = function() {  console.log(this);}var testThis = new GetThis();

输出结果:

  1. GetThis {}
    1. __proto__:Object
      1. constructor:()
      2. __proto__:Object


在apply中,this 指向传入的对象

var GetThis = function(str) {}GetThis.prototype.getString = function() {  console.log(this);}var obj = {str: "I can't guess this!"};GetThis.prototype.getString.apply(obj);


输出:

  1. Object {str"I can't guess this!"}
    1. str:"I can't guess this!"
    2. __proto__:Object



参考:道格拉斯的语言精粹

1 0
原创粉丝点击