了解“ This”关键字时出现的问题

时间:2019-03-11 20:29:04

标签: javascript

为什么在下面的代码中,我没有看到输出为T12345 ABC,而是看到了undefined undefined.

我之所以期望T12345 ABC是因为myCarDetails现在是指全局上下文和global context have registrationNumber and brand defined

var registrationNumber = "T12345";
var brand =  "ABC";

var car = { 
    registrationNumber: "T12345",
    brand: "ABC",

    displayDetails: function(){
        console.log(this.registrationNumber + " " + this.brand);
    }
}

var myCarDetails =  car.displayDetails;
myCarDetails();

1 个答案:

答案 0 :(得分:0)

当我们尝试访问对象本身的任何属性时,该对象本身就是函数,在这种情况下,访问该属性的方式是-

var myCarDetails = car.displayDetails();

myCarDetails

完整的工作代码如下->

var car = {         registrationNumber:“ T12345”,

         brand: "ABC",

         displayDetails:  function() {

         console.log(this.registrationNumber + " " + this.brand);
         }
       }

var myCarDetails = car.displayDetails();

myCarDetails;

其他资源-> https://www.w3schools.com/jS/js_objects.asp