美文网首页
js 函数中this的指向(部分)

js 函数中this的指向(部分)

作者: newway_001 | 来源:发表于2019-02-26 09:02 被阅读0次

在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了

function Foo(){
    this.name='kkk';
    this.year=2019;
    console.log(this);//window
    console.log(this.year)//2019
}
Foo()
function Foo(){
    this.name='kkk';
    this.year=2019;
    console.log(this);  //Foo{name:'kkk',year:2019}
    console.log(this.year)//2019
}
var a=new Foo();
console.log(a.name)//'kkk'
console.log(a.year)//2019

直接调用构造函数的this与new的对象的this不一样

var obj={
    x:10,
    fn:function(){
        console.log(this);
        console.log(this.x)
    }
}

obj.fn();
//{ x: 10, fn: [Function: fn] }
//10

函数作为对象的一个属性,并且作为对象的一个属性被调用时,函数中的this指向该对象。

var obj={
    x:10,
    fn:function(){
        console.log(this);
        console.log(this.x)
    }
}

f=obj.fn;
f();
//window
//undefined

fn函数被赋值到了另一个变量中,并没有作为obj的一个属性被调用,那么this的值就是window,this.x为undefined

相关文章

  • js 函数中this的指向(部分)

    在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了 直接调用构造函数的this...

  • this

    this在js中主要研究的是函数中的this,不代表函数外没有this,函数外的this指向window js中的...

  • 关于js函数中this的指向的问题

    @(javascript)[JavaScript中this的指向] 关于js函数中this的指向的问题 javas...

  • JavaScript中this使用

    JS中this指向 this在全局作用于下指向window 函数中使用的this指向: 函数在调用时,JavaSc...

  • 关于js中this指向的那些事

    this是JS中的关键字,this的指向中函数定义时确定不了,只有 函数指向的时候才能确定this到底指向谁,th...

  • js中this问题小结

    在使用js中的this时,由于js的语法规则,this的指向是会改变的,js中的this指向是根据函数在执行时的作...

  • js中的this

    目标:js中this的指向? 问题的引出 指出this指向什么 js中函数的三种调用形式 func(p1, p2)...

  • js 函数中this指向谁

    一句话总结 谁调用函数,this就指向谁 注意点 1.this指向的,永远是对象2.this指向谁, 不取决与th...

  • es6(class)

    js中的私有方法 _privateMethod(){}形式 关于this 函数中的this指向函数的调用者unde...

  • JS高级-函数中this的指向

    普通模式下:普通函数中的this?调用的时候是window.f1(),window可省略 ...

网友评论

      本文标题:js 函数中this的指向(部分)

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