user8783104
user8783104

Reputation: 185

javascript - How to define a property within a function?

So I can define a property on a function from the outside such as: createNewPerson.hmm = 3; and I get the result 3 when I use the alert. However if I try to do the same but from within a function (as in define a property within a function) it doesn't work.. I tried all the commented lines below. Is there a different way to achieve this or is it simply not possible? If it's not possible, then how does javascript append the .hmm property to the function and later call it?

Full code:

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);

Upvotes: 2

Views: 123

Answers (2)

Guillaume CR
Guillaume CR

Reputation: 3026

I think you are trying to create objects. In javascript, you do it this way:

function Test(){
  this.foo = "bar";
  this.func = function(){
    console.log(this.foo);
  }
}

const test = new Test();
test.foo = "baz";
test.func(); //Will print "baz".

note the use of "new". This is what enables the mechanism of allowing code to modify properties of object. The modified values of the properties is then accessible by the object itself.

Upvotes: 1

Ferhat BAŞ
Ferhat BAŞ

Reputation: 797

Hi please try below code,

jsFiddle

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
this.hello = "hgfg";
this.name = name;
}
var cnp = new createNewPerson('de');
cnp.hmm = 3;
alert(cnp.hmm);
alert(cnp.hello);
alert(cnp.name);

Upvotes: 0

Related Questions