0

The following is the code

function add() {
  var counter = 0;
  this.num = 0;
  function plus (){ return counter +=1;}
  plus();
  return counter;
}

console.log(add.num); //outputs :undefined

Function name can be treated as reference of a function object, so the num is the property of add function object, the outputs could have been 0. But the result is not like so, why?

If i change the code to:

function add() {
      var counter = 0;
      this.num = 0;
      function plus (){ return counter +=1;}
      plus();
      return counter;
    }
var obj = new add();
    console.log(obj.num); //outputs : 0

it works correctly. Can anyone explain this? Many many many thanks.

9
  • console.log(this) in the function body. Commented Jan 30, 2015 at 2:54
  • num is not a property of the add function object. It's a property of the object that you create with new add. Commented Jan 30, 2015 at 2:54
  • @Barmar " It's a property of the object that you create with new add" --- that's not entirely correct. add.call(anyOtherObject); Commented Jan 30, 2015 at 2:55
  • What happens if you try console.log(new add().num); Commented Jan 30, 2015 at 2:57
  • 1
    @FelixKling I didn't. My point was for the OP to compare this inside a call and console.log(add) outside and see they are different things. So the OP could see their mistake immediately, without too much of theory Commented Jan 30, 2015 at 3:09

4 Answers 4

2

this refers to current instance of your function. until you create a new instance using new add() this will refer to window object.

add.num will check if add has a property named num. Which is false because add refers to a function definition not an instance/object of function.

function add() {
  var counter = 0;
  this.num = 0;
  function plus (){ return counter +=1;}
  plus();
  return counter;
}

console.log(add.num); //outputs :undefined  because add=function(){};

while in another case, when you create object using new it returns you a javascript object having all the public properties.

///obj=Object{ num : 0};

function add() {
      var counter = 0;
      this.num = 0;
      function plus (){ return counter +=1;}
      plus();
      return counter;
    }
var obj = new add();
    console.log(obj.num); //outputs : 0 because obj is {num:0}

Fiddle to play: http://jsfiddle.net/ZpVt9/76/

Sign up to request clarification or add additional context in comments.

15 Comments

'this will refer to window object.' is not correct. this points to global object which may be window if the script is executed inside a browser.
Thats more of depends on the scope of execution. I assumed he is executing in window global scope.
@Vijay well, it makes sense to add some words about the global object though.
"add" has the property named "num", because if i add "add.num = 1 before console statement", then console.log(add.num), the output is 0;
@Vijay " javascript standerds says to add properties using prototype" --- it does not. You are free to add properties to objects without using prototypes.
|
1

It will help to read-up on this in JavaScript: MDN

When you do new add(), the interpreter creates a new JavaScript Object/Hash and binds it to this variable in the function. So this is valid inside the scope of the function.

When you don't do a new you are calling the function without a context, so this is undefined in such cases (in 'use strict' mode).

You can explicitly pass a context to Functions using Function.apply/Function.call/Function.bind

1 Comment

Could you kindly provide other tutorial about "this"? The access to MDN is blocked by my company, so sad.
1

this inside a function points to different object depending on how the function is called:

  1. If the function is called in the global context (outside any function) this points to global object (which is window if the script is executed within a browser). console.log(this === window) will output true.
  2. If this is referred inside a function, then it depends if we have set strict mode.

    • If the code is in strict mode then this will be undefined unless we explicitly assign it to something.

    • If the code is not in strict mode then this will point to global object. (Which is again window if script is executed in a browser).

  3. If function is used as constructor to make new objects then this points to the new object being made.

  4. If function is used as object method then this points to the object method is called on.

More explanation with examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


Every function is an object in JavaScript. But as you can see from above explanation none of the ways this points to function object itself from the same function body. Thus the only way you can set function's property is by directly assigning it to the function without using this.

There is another way of adding a property to functions. This is a very bad idea of doing so as adding any property this way will reflect in all functions used. Every function is linked to Function.prototype object. Thus adding any property in this object will get reflected in all functions.

Function.prototype.someProperty = 1;
//now try accessing it via any function object
console.log(add.someProperty); //should print 1 to console.

Comments

-2

"num" is not a property of the "add" function is a property of the object created and returned by that function if you want to add num to your add function you need to do

add.prototype.num=0; 

and remove it from your objects definition

10 Comments

"is a property of the object created and returned by that function" --- it's a property of a bound object, which may be created anywhere.
by defining any property/function in the prototype of a constructor, you make it part pf the function and not bound to the object, hence you can do, function.property, because it belongs to the functions prototype and it will be available to all the objects created by that function
@DayanMorenoLeon well, I'm not an OP and I understand how it works. My point was that your current answer does not clarify anything to the OP (which we can see after their comment above)
Do you seriously suggest me to read about it or you confuse me with OP? Take a second and compare a name who asked this question then mine.
I did not say it's incorrect. I'm just saying that it's not helpful to OP. Just compare with another +1'd answer To clarify: I still didn't downvote you here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.