简体   繁体   中英

Where does property when added to function object

function foo()
{
       var a=5;
 }

Since above function is JavaScript object so we can add properties to it like foo.p=6 .But while doing console.log(foo) i am not able to see the p property of object but is accessible through foo.p and foo['p'].

Also i am not able to access foo.a if we consider foo as JavaScript object.

Try console.dir(foo); instead, which lists the properties of the object. concole.log simply outputs some representation of the value, the browser thinks would be useful.

foo.a can't work. a is a local variable, not a property, and only exist while foo is executed.

When logging an object, the browser will choose how to render it in the console. This may be as primitive as calling .toString() on it, or as complex as giving you the ability to navigate its properties.

Furthermore, the console is not a standard. Browsers may implement it however they like, although for convenience they will keep to a common style. Ultimately, however, this means they will be different.

Internet Explorer:
IE

Google Chrome:
铬

Notice how I had to use console.dir() to force Chrome to give me a navigable view of the object, rather than its simple .toString() representation.

"a" is a local variable, this not accessible from outside the function.

you'd like something like this:

var myClass = function(){
this.foo = 'bar';
}

var myInstance = myClass();
myInstance.foo // 'bar'

or as a plain object:

var myObj = {
foo: 'bar'
}

myObj.foo // 'bar'
myObj.foo = 123;
myObj.foo // 123

There are few ways of achieving that. One is using objects in Javascript and another one with the called "Module Pattern". For using objects, you can do:

function MyObject() {
  this.foo = "myObj";
}
var mo = new MyObject();
console.log(mo.foo); //Will print "myObj".

Module pattern works as below:

var MP = (function(){}(
  var foo = "MP";
  return {
    foo : foo
  }

));
console.log(MP.foo); // Will print "MP"

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