14 Star 80 Fork 23

北京大学-张齐勋 / 移动端开发入门实践

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JS_this.md 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
张齐勋 提交于 2021-03-01 20:13 . update

面向对象语言中this表示当前对象的一个引用。但在JavaScript中this不是固定不变的,它会随着执行环境的改变而改变。

  • 在方法中,this 表示该方法所属的对象。
  • 在函数中,this 表示全局对象。
  • 在函数中,在严格模式下,this 是未定义的(undefined)。
function funabc(){
    console.log(this);
}

var abc = {
    type:1,
    color:"red",
    getColor:function(){
        console.log(this);
        return this.color;
    }
};

console.log(abc.getColor());

funabc();
$ node js.js 
{ type: 1, color: 'red', getColor: [Function: getColor] }
red
<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Getter]
  }
}

严格模式

"use strict";
function funabc(){
    console.log(this);
}

var abc = {
    type:1,
    color:"red",
    getColor:function(){
        console.log(this);
        return this.color;
    }
};

console.log(abc.getColor());

funabc();
$ node js.js 
{ type: 1, color: 'red', getColor: [Function: getColor] }
red
undefined
JavaScript
1
https://gitee.com/ss-pku/webdev.git
git@gitee.com:ss-pku/webdev.git
ss-pku
webdev
移动端开发入门实践
master

搜索帮助