zoukankan      html  css  js  c++  java
  • JavaScript中的关于this

    this在js中是一个特别的关键字,被自动保存在所有函数的作用域中。

    为什么要用this

    this提供一个对象方式隐式传递一个对象的引用,因此可以将api设计的简洁并且容易复用。看下面两段代码的比较:

    function identify() {
            return this.name;
        }
        function speak() {
            return "hello,i am " + identify.call(this);
        }
        var me = {
            name:"tony"
        };
        var you = {
            name:"walker"
        };
        var man = identify.call(you);
        console.log(man); //walker
        var boy = speak.call(me);
        console.log(boy); //tony
    this Code
    function identify(context) {
            return context.name;
        }
        function speak(context) {
            return "hello i am " + identify(context);
        }
        var me = {
            name:"tony"
        };
        var you = {
            name:"walker"
        };
        console.log(identify(me));
        console.log(speak(you));
    context Code

    this误解

    1.this指向函数自身。下面的代码让大家看到this并不像我么所想的那样指向函数本身。

    function foo(i) {
            console.log("foo: " + i);
            this.count++;
        }
        foo.count = 0;
        for(var i =0;i<10;i++){
            if(i>5){
                foo(i);
            }
        };
        console.log(foo.count); //0

    js把函数看成一个对象,可以在函数调用时存储状态(属性的值),执行foo.count =0时,的确想函数添加了一个属性count。但是函数内部代码this.count中的this并不指向函数对象。

    2.this指向函数的作用域。需要明确的是this在任何情况下都不指向函数的的词法作用域。

    function boo() {
            var a = 0;
            this.bar();
        }
        function bar() {
            console.log(this.a); //a is undefined
        }

    this到底是什么

    this是在运行时绑定的,并不在编写时绑定,它的上下文取决于函数调用时的各种条件。this绑定和函数申明没有关系,只取决于函数的调用方式。当函数被调用时,会创建一个活动记录,这个记录会包含函数在那里被调用(调用栈),调用方式,传参方式等。可以说谁调用this就指向谁。

    this实际上是在函数调用的时候发生绑定,它指向什么完全取决于函数在那里被调用。

    下一篇文章会详细的说明this

  • 相关阅读:
    基于摸板匹配的目標跟蹤算法
    spoj 2713 Can you answer these queries IV
    zoj 3633 Alice's present
    hdu 3642 Get The Treasury
    poj 1195 Mobile phones
    poj 2760 End of Windless Days
    zoj 3540 Adding New Machine
    spoj 1716 Can you answer these queries III
    spoj 1043 Can you answer these queries I
    spoj 2916 Can you answer these queries V
  • 原文地址:https://www.cnblogs.com/wangwenhui/p/7625699.html
Copyright © 2011-2022 走看看