简体   繁体   中英

Object function returns function instead of value

I have a really rookie question....

If I define a JS object, and I use a function to generate a property value, why does the property value return a function instead of the generated value?

Example:

var object = {
  bla: 1,
  days: [],
  test : function(){
    return 'bla';
  }
}

console.log(object.test);

I would expect object.test to be 'bla'. Instead it's function(){ return 'bla'; } function(){ return 'bla'; } ... Why?

you have to execute that function, in this way: console.log(object.test());
or, as pointed out by @YuriiKovalenko, you can write the function like this:

var object = {
  bla: 1,
  days: [],
  test : (function(){ return 'bla'; })()
}

and then console.log(object.test); will give you "bla"

Cause you set the value of object.test as a function in

var object = {
  bla: 1,
  days: [],
  test : function(){
    return 'bla';
  }
}

if you want to do so you have to get the value you have to execute object.test()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM