Defining an 'implied' method of a Javascript object -


let's have object, foo:

var foo = {     name: "fooname",     consolelog: function() {console.log("foo!")} } 

...but don't want have specify foo.consolelog() in order call function, want call foo() same effect, and keep of other specifications of object, name shown above, foo.name should still return fooname.

in other words, how can manipulate foo() log foo! console, and foo.name return fooname?

it may worth noting, too, foo sub-object of object.

so, may more this:

var bar = {     foo: {         name: "fooname",         consolelog: function() {console.log("foo!")}     },     name: "barname" } 

i trying search this, didn't know call -- main function? no, returned java. implied function? no, results didn't help... i'm here.

how can this?

you this:

var bar = {   foo: function fooname() { console.log('foo!'); },   name: 'barname' }; bar.foo.anypropertybutname = 'anyvalue'; 

this way foo function (and can called way: bar.foo();) , have name property value of fooname.

if still need bar.foo.consolelog function add:

bar.foo.consolelog = bar.foo; 

Comments