JavaScript 中的this

在开发过程中我们经常用在函数中用到this,但this到底是什么呢?

———所有 javaScript 的代码都是在chrome 下 非严格要求下执行。

1、首先看一下,this的类型。

       (function () { console.log( typeof this);}) ();

结果:

     object。

this是一个对像,是什么对像,是function的prototype,还是其他的呢?


2、执行 :

        代码1: 

                    (function () { console.log( this);}) ();

                结果 :

                        

                 是window。

        代码2:

                var TestObj = {
                    p1: "属性1",
                    p2: "属性2",
                    fun1: function () {
                           console.log( this);
                    }
                };
               TestObj.fun1();

          执行结果:

         
          在段代码中它是fun1所在的对象TestObj


      代码3:

 <!DOCTYPE html>
 <html lang="zh-CN">
<head></head>
<body > 
    <div id='btnDivId'>
        <input type="button" value="PrintBtn" style="float: left; _padding: 2px 4px;" id="clickBtnId">
    </div>    
</body>
<script>
function clickFun () {

    console.log(typeof this);
    console.log( this);
}
document.getElementById("clickBtnId").addEventListener ('click',clickFun) ;
</script>
</html>

结果:



是:input对象。


代码4:

var testObj = {
    p1: this,
    p2: {p2this: this}
}
console.log(testObj.p1)
console.log(testObj.p2.p2this)

结果:



3、可以下一下大体的结论:

     this是调用它的函数或对象所在的上下文环境对象。



猜你喜欢

转载自blog.csdn.net/zhaozhbcn/article/details/43700371