Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript Object nothing but an associative array?

Tags:

javascript

Ok am just going through basics of JavaScript and I was learning objects where I came across this example...

JavaScript

var person = {
   firstname : "Smith",
   lastname  : "Bach"
};

And what we write in PHP is

$person = array(
    "firstname"=>"Smith", 
    "lastname"=>"Bach"
);

So is this the same thing or am making a mistake in understanding the concept?

like image 270
Mr. Alien Avatar asked Dec 25 '12 14:12

Mr. Alien


1 Answers

No, objects are more than that.

Object is indeed a map/dictionary, but additionally every object inherits some of the properties (key-value pairs) from another object. That other object is called prototype.

For example:

var o = {
    x: 1
};

console.log(o.x === undefined);           // false, obviously
console.log(o.toString === undefined);    // false, inherited from prototype

Most commonly a prototype is set by creating an object with a constructor function:

var d = new Date();
console.log(d.hasOwnProperty('getYear'));     // false, it's inherited

EDIT:

Here's how the prototype works using constructor functions (it's one of the ways to do OOP in JS):

// constructor function
// starts with capital letter, should be called with new
var Person = function (name, age) {
    // set properties of an instance
    this.name = name;
    this.age = age;
};

// functions to be inherited are in the prototype
Person.prototype.sayHello = function () {
    return this.name + ' is ' + this.age + ' old';
};

// new:
// - creates the object
// - sets up inheritance from prototype
// - sets the object as the context of the constructor function call (this)
var p = new Person('Jason', 27);

console.log(p.sayHello());
like image 117
Stefan Avatar answered Sep 28 '22 05:09

Stefan