Home  >  Article  >  Web Front-end  >  About the understanding of this in js function

About the understanding of this in js function

一个新手
一个新手Original
2017-09-22 10:31:361821browse

//关于this的问题 第一个情况:
    function Foo() {
        this.name=10;
        this.age=100;
        console.log(this)   //{name:10, age:100}
    }
//    var p=new Foo();   new 一个对象,this指的就是即将new出来的对象
//    Foo()      调用情况下,this指window  输出{window}
//关于this的问题 第二种情况:var obj={
        x:5,
        fn:function () {
            console.log(this);   //obj{x:10,fn:function}
            console.log(this.x);  //5
        }
};
obj();
    //函数作为对象的一个属性被调用时,this指该对象,即obj
//关于this的问题 第三种情况:var obj= {
    x: 10,
    fn: function () {
        console.log(this);   //Window
        console.log(this.x);  //undefined
    }
};
var fun=obj.fn;
    fun()
    //这里fn函数被赋值到另一个变量中,没有作为obj一个属性被调用,则this指window//关于this的问题 第四种情况:
    var obj={ x:20}
    var fn =function () {
            console.log(this);  //Object {x:20}
            console.log(this.x)  //20
        }
    fn.call(obj);
    //当一个函数被call或apply调用时,this则取传入的对象的值或者:var x=20;var fn = function(){	console.log(this)    //window	console.log(this.x)   //20};fn(); //调用fn函数时,this指的是window//关于this的问题 第五种情况:var obj={
    x:10,
    fn:function(){
        function f(){
            console.log(this);  //window
            console.log(this.x)  //undefined
        }
        f()
    }
};
obj.fn()
//    函数f虽然是在函数内部定义的,但仍然是普通函数,this指window.

The above is the detailed content of About the understanding of this in js function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn