如何在JavaScript中获取“this”关键字的值?

时间:2014-08-22 04:46:46

标签: javascript

如何在JavaScript中的函数中获取“this”关键字的值?或者当调用对象引用“this”关键字时,如何判断哪个对象调用函数或方法?

var newObject = {name : "John", newFunction : function () { alert(this)}}
newObject.newFunction() .// output --> [object Object]

我希望输出为[object newObject];

4 个答案:

答案 0 :(得分:0)

您可以使用console.log

查看this的值
var newObject = {name : "John", newFunction : function() { console.log(this); }}

newObject.newFunction();

答案 1 :(得分:0)

无论你给出什么变量名,你都会得到[对象对象]。如果要查看对象属性,可以使用。

 var newObject = {
     name: "John",
     newFunction: function () {
         alert(JSON.stringify(this))
     }
 };
 newObject.newFunction();

答案 2 :(得分:0)

获取this值的一种方法是使用console.dir()

只需将您的代码更改为:

var newObject = {name : "John", newFunction : function () { console.dir(this)}};
newObject.newFunction();

Working Demo

答案 3 :(得分:0)

关于alert(obj)和对象的[ToString](通过this)的假设是不正确的,并在下面进行了探讨。

var newObject = {
    newFunction : function () { return this; }
}
var obj = newObject.newFunction();
// Trivially, `this` is returned from the function showing that it is
// the same object as the reciever the property was resolved from.
console.log("same object? " + (obj === newObject))

// And this results in [object Object], which is the same as "" + newObject
// since newObject === obj, as previously explored.
// (The name of the function/context does not matter here, as `toString()`
//  is not magically changed; "[object Object]" is the output for [ToString]
//  of an arbitrary object.)
var str = "" + obj  // -> "[object Object]"
console.log(str)    

// Leading to the predictable and see output of [object Object]
// in all three of the alert calls below.
alert(obj)          // which is is the same the following ..
alert(str)          // or with substitution ..
alert("" + obj)

// And depending upon browser and version, explore the "real" object:
console.dir(obj)
console.log(obj)

所以,tldr:停止使用alert进行调试。在某些浏览器中使用console.dir(或console.log),在这种情况下,参数会自动转换为字符串;或者,附加一个断点并检查呼号帧,包括this,live。