美文网首页
this的最基本五种指向

this的最基本五种指向

作者: JSONYUAN | 来源:发表于2019-03-05 14:18 被阅读0次

<script>
/*
* this 指向<调用>该<函数>的那个<对象>
*
*
* 场景1:
* 直接调用 普通函数
* this 指向 window,因为默认是 window 调用该函数
*
* 场景2:
* 事件处理函数
* this 指向 触发事件处理函数的那个事件源 对象
*
* 场景3:
* 对象方法
* this 指向调用该方法(函数)的对象
*
* 场景4:
* 定时器内的回调函数
* this 指向 window 对象,因为定时器是 window对象下的一个方法而已
*
* 场景5:
* 构造函数内部的this
* this 指向当前构造函数实例对象
*
*
* */

/* 场景1:普通函数 */
// function fn() {
//     console.log(this);    //  this === window
// }
// fn();

/* 场景2:事件处理函数 */
// var btn = document.getElementById('btn');
// btn.onclick = function () {
//     console.log(this);         // this === btn
// };

/* 场景3:对象的函数 */
// var obj = {
//     name: '李狗蛋',
//     age: 18,
//     sayHi : function () {
//         console.log(this);     // this === obj
//     }
// };
// obj.sayHi();

/* 场景4:定时器回调函数 */
// var timer = window.setInterval(function () {
//     console.log(this);        // this === window
// },1000)

/* 场景5:构造函数 */
function Person(name) {
    this.name = name;
    console.log(this);     // this 指向实例对象,实例对象还没赋值给变量,所以判断不了
}

var p1 = new Person('小明');

</script>

相关文章

  • this的最基本五种指向

    /** this 指向<调用>该<函数>的那个<对象>*** 场景1:* ...

  • 最基本的JavaScript面试问题及答案

    25个最基本的JavaScript面试问题及答案 this的指向 在es5中,在内部函数中的this将指向全局的w...

  • bind,call和apply的应用

    bind,call和apply都可以用于改变一个函数的this指向,这也是他们最基本的作用. 通常,一些高级函数中...

  • this的指向和改变this的指向

    一、this的指向 普通函数调用 function fn(){ console.log(this) //thi...

  • this的指向

    this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向...

  • this的指向

    整理自: https://zhuanlan.zhihu.com/p/23804247 https://zhuanl...

  • this的指向

  • this的指向

    函数中的this是在运行时候决定的,而不是函数定义时全局环境中的this指window其他函数中的this指向调用...

  • this的指向

    如果是一般函数,this指向全局的对象window 在严格模式下“use strict”,this为undefin...

  • this的指向

    this的指向分为四大类: 一:作为对象的方法调用 二:作为普通函数调用 三:构造器调用 四:Function.p...

网友评论

      本文标题:this的最基本五种指向

      本文链接:https://www.haomeiwen.com/subject/hdonuqtx.html