JS关于dom结构中的this该怎么判断?

代码如下:

var body = document.querySelector('body');
body.style.background = '#000';
console.log(body.style.background);
//    "rgb(0, 0, 0)"
body.style.background.substr(this.length);
//    "gb(0, 0, 0)"

这里面的this到底指向了哪个东西? 单独log出来找不到相关length为1的对象啊?

PS: 原本打算简化相应的代码, substr用来过滤px|vh等单位

阅读 4.3k
7 个回答

函数直接调用,this指向undefined。 作为对象调用时,this指向该对象。 非严格模式下,this指向undefined时,会自动改为指向window。 你代码这里是直接调用this,且为非严格模式,所以指向的是window. 你可以自己console.log(this)查看啊

我觉得你应该仔细看看substr方法的参数以及返回值

直接放在script里面的话,这里this指window,你可以

    window.length = 2;
    console.log(body.style.background.substr(this.length));

windowlength属性

MDN

this是window,输出这句话console.log(this);在window属性里发现其length是0

this指向window;

var _color = body.style.background;
    _color.substr(color.length); 

在js中this指的是,调用函数的对象,例如
div1.onclick = function (){

this.innerHTML = '我是DIV1'

}
this为div1
在你的代码中,this指向的是window DOM的根节点

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题