JS ‘this’ and Objects

JavaScript is a language designed with object-based paradigms (to read: Is js a true oop language). An object is akin to real life objects, and has a collection of properties (with key-value pair associations). When the property’s value is a function, it is known as a method.

Almost all values in JavaScript are objects, except primitives, because they are immutable. Primitives, therefore, do not have properties or methods.

There are five types of primitives: boolean, number, string, null, and undefined.

As an example: if var x = 3 you can change the value of x, but the number 3 will always be 3.

x has only one property in this case, but you can create your own Objects with multiple variables. This object

There are various ways of creating Objects:

Object literal

var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};

Keyword new

var person = new Object();
person.firstName = “John”;
person.lastName = “Doe”;
person.age = 50;
person.eyeColor = “blue”;

Both works the same for creating single Objects, but if you need multiple Objects of the same type, you can use Object constructors instead:

Object Constructors

function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

var myFather = new Person(“John”, “Doe”, 50, “blue”);
var myMother = new Person(“Sally”, “Rally”, 48, “green”);

You can access the values of an Object’s properties by either the dot or brackets notations.

objectName.property

objectName[“property“]

The for… in loop loops through each property of an Object:

var person = {fname:”John”, lname:”Doe”, age:25};

for (x in person) {
console.log(x); //displays all keys
console.log(person[x]); // displays all values}

Another method to get the keys of an Object,

console.log(Object.keys(person));

You can also add and delete properties after an object is created, like so:

person.nationality = “English”;

delete person.age;

Indexing

Indexing in objects goes by numbers first, then strings in the order you created it in. Therefore, you must always refer to an object by what you initially defined it. The exception to this rule is array-like objects reflected from HTML, such as forms. You can refer to the second <FORM> tag in a document with name attribute “myForm” by document.forms[1] or document.forms[“myForm”], or even document.forms.myForm.

Object Methods

‘this’ keyword

If used inside a method, ‘this’ refers to the ‘owner’ of the function.

var person = {
firstName: “John”,
lastName : “Doe”,
id       : 5566,
fullName : function() {
return this.firstName + ” ” + this.lastName; //returns John Doe
}
};

In the example above, the ‘owner’ is the person object.

‘this’ has different values depending on where it is used. It behaves differently in strict mode, which does not allow default binding and returns undefined when used in a function.

Function (use strict)

“use strict”;
function myFunction() {
return this;
}

//this == undefined

In a JavaScript function, the owner of the function refers to the Global object, which is the object Window in a browser window..

Function (default)

function myFunction() {
return this;
}

//this == [object Window]

When used alone, the owner is the Global object.

document.getElementById(“demo”).innerHTML = this;

//this == [object Window]

‘this’ in HTML event handlers refers to the HTML element that received the event:

<button onclick=”this.style.display=’none'”>
Click to Remove Me!
</button>

You can also pass the value of ‘this’ from one context to another:

call() & apply()

var obj = {a: ‘custom’};

var a = ‘global’;

function whatIsThis(){
return this.a;}

whatIsThis(); // ‘global’, unless strict mode
whatIsThis.call(obj); // ‘custom’
whatIsThis.apply(obj); //’custom’

From MDN: “While the syntax of apply() is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.”

Resources:
https://www.w3schools.com/js/js_object_definition.asp
https://www.w3schools.com/js/js_this.asphttps://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

 

1 thought on “JS ‘this’ and Objects

  1. […] Previously, we learned how to construct a new object with an object constructor. […]

    Like

Leave a reply to JS: Constructor, Prototype, Classes – Stuff I Have Learnt Cancel reply

Design a site like this with WordPress.com
Get started