Javascript assign this in function

Object methods, «this»

Objects are usually created to represent entities of the real world, like users, orders and so on:

And, in the real world, a user can act: select something from the shopping cart, login, logout etc.

Actions are represented in JavaScript by functions in properties.

Method examples

For a start, let’s teach the user to say hello:

let user = < name: "John", age: 30 >; user.sayHi = function() < alert("Hello!"); >; user.sayHi(); // Hello!

Here we’ve just used a Function Expression to create a function and assign it to the property user.sayHi of the object.

Then we can call it as user.sayHi() . The user can now speak!

A function that is a property of an object is called its method.

So, here we’ve got a method sayHi of the object user .

Of course, we could use a pre-declared function as a method, like this:

let user = < // . >; // first, declare function sayHi() < alert("Hello!"); >// then add as a method user.sayHi = sayHi; user.sayHi(); // Hello!

When we write our code using objects to represent entities, that’s called object-oriented programming, in short: “OOP”.

OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That’s architecture, and there are great books on that topic, like “Design Patterns: Elements of Reusable Object-Oriented Software” by E. Gamma, R. Helm, R. Johnson, J. Vissides or “Object-Oriented Analysis and Design with Applications” by G. Booch, and more.

Method shorthand

There exists a shorter syntax for methods in an object literal:

// these objects do the same user = < sayHi: function() < alert("Hello"); >>; // method shorthand looks better, right? user = < sayHi() < // same as "sayHi: function()" alert("Hello"); > >;

As demonstrated, we can omit «function» and just write sayHi() .

To tell the truth, the notations are not fully identical. There are subtle differences related to object inheritance (to be covered later), but for now they do not matter. In almost all cases, the shorter syntax is preferred.

“this” in methods

It’s common that an object method needs to access the information stored in the object to do its job.

For instance, the code inside user.sayHi() may need the name of the user .

To access the object, a method can use the this keyword.

The value of this is the object “before dot”, the one used to call the method.

let user = < name: "John", age: 30, sayHi() < // "this" is the "current object" alert(this.name); >>; user.sayHi(); // John

Here during the execution of user.sayHi() , the value of this will be user .

Technically, it’s also possible to access the object without this , by referencing it via the outer variable:

…But such code is unreliable. If we decide to copy user to another variable, e.g. admin = user and overwrite user with something else, then it will access the wrong object.

let user = < name: "John", age: 30, sayHi() < alert( user.name ); // leads to an error >>; let admin = user; user = null; // overwrite to make things obvious admin.sayHi(); // TypeError: Cannot read property 'name' of null

If we used this.name instead of user.name inside the alert , then the code would work.

“this” is not bound

In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function, even if it’s not a method of an object.

There’s no syntax error in the following example:

The value of this is evaluated during the run-time, depending on the context.

For instance, here the same function is assigned to two different objects and has different “this” in the calls:

let user = < name: "John" >; let admin = < name: "Admin" >; function sayHi() < alert( this.name ); >// use the same function in two objects user.f = sayHi; admin.f = sayHi; // these calls have different this // "this" inside the function is the object "before the dot" user.f(); // John (this == user) admin.f(); // Admin (this == admin) admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)

The rule is simple: if obj.f() is called, then this is obj during the call of f . So it’s either user or admin in the example above.

We can even call the function without an object at all:

function sayHi() < alert(this); >sayHi(); // undefined

In this case this is undefined in strict mode. If we try to access this.name , there will be an error.

In non-strict mode the value of this in such case will be the global object ( window in a browser, we’ll get to it later in the chapter Global object). This is a historical behavior that «use strict» fixes.

Usually such call is a programming error. If there’s this inside a function, it expects to be called in an object context.

If you come from another programming language, then you are probably used to the idea of a «bound this «, where methods defined in an object always have this referencing that object.

In JavaScript this is “free”, its value is evaluated at call-time and does not depend on where the method was declared, but rather on what object is “before the dot”.

The concept of run-time evaluated this has both pluses and minuses. On the one hand, a function can be reused for different objects. On the other hand, the greater flexibility creates more possibilities for mistakes.

Here our position is not to judge whether this language design decision is good or bad. We’ll understand how to work with it, how to get benefits and avoid problems.

Arrow functions have no “this”

Arrow functions are special: they don’t have their “own” this . If we reference this from such a function, it’s taken from the outer “normal” function.

For instance, here arrow() uses this from the outer user.sayHi() method:

let user = < firstName: "Ilya", sayHi() < let arrow = () =>alert(this.firstName); arrow(); > >; user.sayHi(); // Ilya

That’s a special feature of arrow functions, it’s useful when we actually do not want to have a separate this , but rather to take it from the outer context. Later in the chapter Arrow functions revisited we’ll go more deeply into arrow functions.

Summary

  • Functions that are stored in object properties are called “methods”.
  • Methods allow objects to “act” like object.doSomething() .
  • Methods can reference the object as this .

The value of this is defined at run-time.

  • When a function is declared, it may use this , but that this has no value until the function is called.
  • A function can be copied between objects.
  • When a function is called in the “method” syntax: object.method() , the value of this during the call is object .

Please note that arrow functions are special: they have no this . When this is accessed inside an arrow function, it is taken from outside.

Tasks

Using «this» in object literal

Here the function makeUser returns an object.

What is the result of accessing its ref ? Why?

function makeUser() < return < name: "John", ref: this >; > let user = makeUser(); alert( user.ref.name ); // What's the result?

Answer: an error.

function makeUser() < return < name: "John", ref: this >; > let user = makeUser(); alert( user.ref.name ); // Error: Cannot read property 'name' of undefined

That’s because rules that set this do not look at object definition. Only the moment of call matters.

Here the value of this inside makeUser() is undefined , because it is called as a function, not as a method with “dot” syntax.

The value of this is one for the whole function, code blocks and object literals do not affect it.

So ref: this actually takes current this of the function.

We can rewrite the function and return the same this with undefined value:

function makeUser() < return this; // this time there's no object literal >alert( makeUser().name ); // Error: Cannot read property 'name' of undefined

As you can see the result of alert( makeUser().name ) is the same as the result of alert( user.ref.name ) from the previous example.

function makeUser() < return < name: "John", ref() < return this; >>; > let user = makeUser(); alert( user.ref().name ); // John

Now it works, because user.ref() is a method. And the value of this is set to the object before dot . .

Источник

The Complete Guide to this in JavaScript

The Complete Guide to this in JavaScript

In JavaScript, every function has a this reference automatically created when you declare it.

JavaScript’s this is quite similar to a this reference in other class-based languages such as Java or C# (JavaScript is a prototype-based language and no “class” concept): It points to the which object is calling to the function (this object sometimes called as context). In JavaScript, however, the this reference inside functions can be bound to different objects depending on where the function is being called.

Here are 5 basic rules for this binding in JavaScript:

Rule 1

When a function is called in the global scope, the this reference is by default bound to the global object ( window in the browser, or global in Node.js). For example:

function foo() < this.a = 2; >foo(); console.log(a); // 2

Note: If you declare the foo() function above in strict mode, then you call this function in global scope, this will be undefined and assignment this.a = 2 will throw Uncaught TypeError exception.

Rule 2

Let’s examine example below:

function foo() < this.a = 2; >const obj = < foo: foo >; obj.foo(); console.log(obj.a); // 2

Clearly, in the above snippet, the foo() function is being called with context is obj object and this reference now is bound to obj . So when a function is called with a context object, the this reference will be bound to this object.

Rule 3

.call , .apply and .bind can all be used at the call site to explicitly bind this . Using .bind(this) is something you may see in quite a lot of React components.

const foo = function() < console.log(this.bar) >foo.call(< bar: 1 >) // 1

Here’s a quick example of how each one is used to bind this :

  • .call() : fn.call(thisObj, fnParam1, fnParam2)
  • .apply() : fn.apply(thisObj, [fnParam1, fnParam2])
  • .bind() : const newFn = fn.bind(thisObj, fnParam1, fnParam2)

Rule 4

function Point2D(x, y) < this.x = x; this.y = y; >const p1 = new Point2D(1, 2); console.log(p1.x); // 1 console.log(p1.y); // 2

The thing you must notice that is the Point2D function called with new keyword, and this reference is bound to p1 object. So when a function is called with new keyword, it will create a new object and this reference will be bound to this object.

Note: As you call a function with new keyword, we also call it as constructor function.

Rule 5

JavaScript determines the value of this at runtime, based on the current context. So this can sometimes point to something other than what you expect.

Consider this example of a Cat class with a method called makeSound() , following the pattern in Rule 4 (above) with a constructor function and the new keyword.

const Cat = function(name, sound) < this.name = name; this.sound = sound; this.makeSound = function() < console.log( this.name + ' says: ' + this.sound ); >; > const kitty = new Cat('Fat Daddy', 'Mrrooowww'); kitty.makeSound(); // Fat Daddy says: Mrrooowww

Now let’s try to give the cat a way to annoy() people by repeating his sound 100 times, once every half second.

const Cat = function(name, sound) < this.name = name; this.sound = sound; this.makeSound = function() < console.log( this.name + ' says: ' + this.sound ); >; this.annoy = function() < let count = 0, max = 100; const t = setInterval(function() < this.makeSound(); // >, 500); >; > const kitty = new Cat('Fat Daddy', 'Mrrooowww'); kitty.annoy();

That doesn’t work because inside the setInterval callback we’ve created a new context with global scope, so this no longer points to our kitty instance. In a web browser, this will instead point to the Window object, which doesn’t have a makeSound() method.

A couple of ways to make it work:

  1. Before creating the new context, assign this to a local variable named me , or self , or whatever you want to call it, and use that variable inside the callback.
const Cat = function(name, sound) < this.name = name; this.sound = sound; this.makeSound = function() < console.log( this.name + ' says: ' + this.sound ); >; this.annoy = function() < let count = 0, max = 100; const self = this; const t = setInterval(function() < self.makeSound(); count++; if (count === max) < clearTimeout(t); >>, 500); >; > const kitty = new Cat('Fat Daddy', 'Mrrooowww'); kitty.annoy();
  1. With ES6 you can avoid assigning this to a local variable by using an arrow function, which binds this to the context of the surrounding code where it’s defined.
const Cat = function(name, sound) < this.name = name; this.sound = sound; this.makeSound = function() < console.log( this.name + ' says: ' + this.sound ); >; this.annoy = function() < let count = 0, max = 100; const t = setInterval(() => < this.makeSound(); count++; if (count === max) < clearTimeout(t); >>, 500); >; > const kitty = new Cat('Fat Daddy', 'Mrrooowww'); kitty.annoy();

Источник

Читайте также:  Питон считывание чисел из файла
Оцените статью