JavaScript Object只是一个关联数组吗?

Mr.*_*ien 8 javascript

好的,我只是通过JavaScript的基础知识,我正在学习objects我遇到这个例子的地方......

JavaScript的

var person = {
   firstname : "Smith",
   lastname  : "Bach"
};
Run Code Online (Sandbox Code Playgroud)

我们用PHP编写的是

$person = array(
    "firstname"=>"Smith", 
    "lastname"=>"Bach"
);
Run Code Online (Sandbox Code Playgroud)

这是同样的事情,还是在理解这个概念时犯了错误?

Ste*_*fan 11

不,对象不止于此.

Object确实是一个map/dictionary,但是另外每个对象都从另一个对象继承了一些属性(键值对).那个其他对象叫做原型.

例如:

var o = {
    x: 1
};

console.log(o.x === undefined);           // false, obviously
console.log(o.toString === undefined);    // false, inherited from prototype
Run Code Online (Sandbox Code Playgroud)

最常见的是通过使用构造函数创建对象来设置原型:

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

编辑:

以下是原型如何使用构造函数(它是在JS中执行OOP的方法之一):

// 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());
Run Code Online (Sandbox Code Playgroud)