Javascript的结果是作为字符串的函数,而不是我所期望的数组元素

Javascript的结果是作为字符串的函数,而不是我所期望的数组元素,javascript,Javascript,我的JavaScript对象中有一个数组,但是当我尝试返回数组的元素时,我得到的函数是字符串,而不是数组元素的值 我的代码是 function Car(make, model){ this.make = make; this.model = model; this.dimensions = [4, 3, 1.8]; this.carLength = function(){ return this.dimensions[0]; }; } var c =

我的JavaScript对象中有一个数组,但是当我尝试返回数组的元素时,我得到的函数是字符串,而不是数组元素的值

我的代码是

  function Car(make, model){
    this.make = make;
    this.model = model;
    this.dimensions = [4, 3, 1.8];
    this.carLength = function(){ return this.dimensions[0]; };
  }

  var c = new Car("Ford", "Escort");

  alert(c.make);
  alert(c.model);
  alert(c.dimensions[0]);
  alert(c.carLength);
前3个警报显示预期数据(“Ford”、“Escort”和4),第4个警报显示以下输出

function(){ return this.dimensions[0]; }

为什么函数被列出而没有执行?

执行函数时需要包含括号

alert(c.carLength());
如果不包括括号,则只是将函数的引用作为变量传递到
alert
函数中。然后,
alert
将对该变量执行
toString()


包含括号时,传递的是执行函数返回的值。

CarInstance.carLength
是一种方法。你必须调用它,否则你只能得到函数
console.log(c.carLength())
因为这是一个函数,所以要在最后执行use()。示例:
alert(c.carLength())
alert(c.carLength());