this的应用场景和固定

  • this是函数执行时才会创建的一个内部对象,表示当前持有该函数的对象

四类场景

  1. 对象内部的属性值为函数,使用对象访问属性并执行函数时。this代表当前对象
var person = {
            name:"tom",
            say:function(){
                console.log(this);
            }
        };
        person.say();
        person.eat = function(){
            console.log(this); 
        };
        person.eat();
  • 为按钮添加点击事件
document.getElementsByTagName('input')[0].onclick = function(){
            console.log(this); //表示input对象
        };
  1. 构造函数中的this,函数执行时this表示新对象
function Person(name,age){
            this.name = name;
            this.age = age;
            console.log(this);
        }
        var p = new Person("tom",28);
  1. 使用call或apply主动修改函数时,this的指向,让其等于call或apply的第一个实参
function getpro(proName){
            return this[proName];
        }
        console.log(getpro("p"));
        console.log(getpro.call(person,"name"));
  • 所有的全局变量都是window的私有属性
  1. 除以上三种场景外,this代表的是window
function fn(){
            console.log(this);
        }
        fn();
  • 函数嵌套函数,无论函数嵌套多少层,都表示window
function fun(){
            console.log(this);
            function fun(){
                console.log(this);
                function fun(){
                    console.log(this);
                }
            }   fun();
            fun();
        }
        fun();

this的固定

document.getElementsByTagName('input')[0].onclick = function(){
            var _t =this;//var _this = this; 这叫this的固定
            colorful();
                function colorful(){

                // document.getElementsByTagName('input')[0].className = "colorful";
                _t.className = "colorful";
            }
        };

            function colorful(-t){
                // document.getElementsByTagName('input')[0].className = "colorful";
                _t.className = "colorful";
            }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,045评论 8 265
  • 1.数据类型 1.1概念篇 7种原始数据类型 引用类型 null是对象吗?为什么? 结论: null不是对象 解释...
    859z阅读 3,089评论 0 0
  • 2018web前端最新面试题总结 一、Html/Css基础模块 基础部分 什么是HTML?答:​ HTML并不是...
    duans_阅读 10,089评论 3 27
  • JavaScript 从交互的角度,描述行为(提升用户体验)。 JavaScript-基础 Github 特点 简...
    LoTwT阅读 1,796评论 0 0
  • JavaScript 历史 JavaScript 作为 Netscape Navigator 浏览器的一部分首次出...
    coderlion阅读 2,394评论 0 1

友情链接更多精彩内容