JS: Objects (Part 2) Methods, Getter & Setters

Methods

A method is a property of an object that is a function. They are defined the same way normal functions are, except they have to be assigned as properties in an object:

var obj = {
foo() {
return ‘bar’;
}
}

console.log(obj.foo());
// expected output: “bar”

Get

A get syntax binds an object property to a function that will be called when the property is accessed.

var obj = {
arr: [‘a’, ‘b’, ‘c’],
get latest() {
if (this.arr.length == 0) {
return undefined;
}
return this.arr[this.arr.length – 1];
}
}

console.log(obj.latest);
// expected output: “c”

Set

Set binds an object property to a function to be called when you try to set the property.

var language = {
set current(name) {
this.arr.push(name);
},
arr: []
}

language.current = ‘EN’;
language.current = ‘FA’;

console.log(language.arr);
// expected output: Array [“EN”, “FA”]

Comparing Objects

Objects are a reference type, and can never be equal, even if they have the same properties. (Think pointers to clones of objects.) Comparing the same object reference with itself, however, returns true. (Think pointers to one object.)

var fruit = {name: 'apple'};
var fruitbear = {name: 'apple'};
fruit == fruitbear; // return false

 

 

 

 

Leave a comment

Design a site like this with WordPress.com
Get started