How u did it?


How u did it?? I tried in all possible solutions from here ...

17 'This' Works for Everyone Error

We started out with a method on the window object:

var setAge = function (newAge) {
    this.age = newAge;

As we will see, this method only works on the window object (in global scope).

console.log(age);          // 25
console.log(window.age);   // 25

This won't be much help in the context of our own custom objects, bob and susan, unless we add the methods to their context.

bob.setAge = setAge;
susan.setAge = setAge;

What we have done is write these as new properties in each object. We do not wish to evaluate them at the time of assignment, hence no (). What is written is the string representation of the method.

function (newAge) {
    this.age = newAge;

Just as above in the window example, if these objects do not have an age attribute, one will be created.

console.log(susan.age);    // 30
console.log(susan.age);    // 25

Note how we invoke the method on the object, and the difference between that an when we copied the method.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.