0

In java script when we make a new constructor function we use "this.property name". We use "this" to refer the object which currently in use. But in a general function we doesn't use "this" keyword. According to my understanding if we use "this" in function it should point to the current function. However when we used, it was not producing the expected result. Why? Example

function greet(name){ console.log("Hello " + this.name); }

Output is "Hello" then blank.

3 Answers3

0

Read this about this

In most cases, the value of this is determined by how a function is called.

Amol Katdare
  • 6,740
  • 2
  • 33
  • 36
0

Because in general function, we are by default referring 'window' object so anything we make it becomes window level object or variable.

Like,

function fun(){
 this.title = "window";
}

fun();

or window.fun(); //both are same. Since we call window.fun, this.title means window.fun.

If you create like this:

var obj = { }

**Now to make title at obj level, you can do like this:

fun.call(obj);

Now you can call obj.title.**

Nitesh
  • 1,490
  • 1
  • 12
  • 20
0

When you use the new keyword in javascript an implicit object is created and returned from the function call. Inside of the function this refers to the newly created object. Calling a function without new does not have the same behavior.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

xarthna
  • 56
  • 5