温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

原生javascript中this几种常见用法总结

发布时间:2020-08-24 19:16:58 来源:脚本之家 阅读:142 作者:巴啦啦小能量 栏目:web开发

本文实例讲述了原生javascript中this几种常见用法。分享给大家供大家参考,具体如下:

this的应用  “是”  代名词

this必须出现在函数里面

//------------------默认绑定
function test (){
  console.log(this.a);//1
}
var a = 1;
test();

this取得是window的对象a;此处默认window

//---------------------隐士绑定?
function test (){
  console.log(this.a);//2
}
var foo = {
  a:2,
  f:test
}
var a = 1;
foo.f();

此处this取得是foo对象的a;

//---------------------隐士绑定 多层调用链?
function test (){
  console.log(this.a);//3
}
var foo = {
  a:3,
  f:test
}
var foo2 = {
  a:4,
  f:foo
}
var a = 1;
foo2.f.f();

此处this取得是foo对象的a,foo2中只起到调用foo,所以thisl指的还是foo;

//---------------------隐士绑定 (隐士丢失) 多层调用链?
function test (){
  console.log(this.a);//1
}
var foo = {
  a:2,
  f:test
}
var a = 1;
var fun = foo.f;
fun();

由于是赋值  调用的是fun(),foo.f 是取函数,但是this的对象是fun,是window对象,所以只能取得全局变量a

//1,this所在的函数是事件处理函数,那么this就是事件源;
var btns = document.getElementsByTagName("button");
获取所有button
for(var i = 0; i < btns.length;i++){
  btns[i].onclick = function(){
    this代表当前事件源
    console.log(this)
  }
}

// 2、this所在函数是构造函数,那么this就是new的对象,并且会生成__proto__属性。
function func(name,age){
  this.name = name;
  this.age = age;
  // console.log(this)
}
let f = new func("z",20);

// 3、this所在函数是类的方法,那么this就是调用方法时的对象
function Fnc(name,age){
  this.name = name;
  this.age = age;
}
Fnc.prototype.eat = function(){
  console.log(this);
}
let fn = new Fnc("a",12);
fn.eat();
let fn2 = new Fnc("b",10);
fn2.eat();

// 4、this的转移 转移到window
var btns = document.getElementsByTagName("button");
//获取所有button
for(let i = 0; i < btns.length;i++){
  btns[i].onclick = function(){
    console.log(this)
    // this代表点击事件源
    setTimeout(function(){
      console.log(this);
      // this代表window对象 发生了转移
    },30)
  }
}
/*
以上所说的所在函数,重点看关键字function。不会受箭头函数的影响
JavaScript中的一切的一切都属于window对象。window对象可以省略。
所有的全部变量,函数,类,都属于window对象。
this的转移:发生在闭包里。*/

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》

希望本文所述对大家JavaScript程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI