关键字this没有给我当前对象,只有它的父对象.如何得到当前对象

The keyword this is not giving me the current object, only its parent. How do I get at the current object?

本文关键字:对象 何得 关键字 this      更新时间:2023-09-26

我正在尝试创建一个指向当前对象/函数的变量。

我错误地认为this会这样做:

var fn1=function(){
    var _this=this;
    _this.prop='hey!';
    console.log(_this);
};

控制台日志输出浏览器窗口对象,这让我感到困惑,直到我读到this:

this关键字功能上下文

谁能解释给我为什么,在javascript中,this指的是父母?

作为所有this的结果,我一直在考虑使用类似this的东西:

var fn2=function(){
    var _this=(function(){
        return this;
    })();
    _this.prop='hey!';
    console.log(_this);
};

但是,是否有更好的方法或简单的正确的方法,我错过了,从内部获得当前对象?

谁能解释给我为什么,在javascript中,this指的是父母?

this的值取决于你如何调用函数。

如果你在对象(foo.method())的上下文中调用函数,那么this就是foo,因为在执行OOP时访问方法所属的对象是有用的。

但是,是否有更好的方法或简单的正确的方法,我错过了,从内部获得当前对象?

当前对象是什么?

如果要使用构造函数,则使用new关键字。

function Dog(name, breed) {
    this._name = name;
    this._breed = breed;
}
var myDog = new Dog("Fifi", "Poodle");
alert(myDog._name);