我正在学习 JavaScript 的基础知识,其中涉及到 对象
,我看到了这个例子...
JavaScript
var person = {
firstname : "Smith",
lastname : "Bach"
};
我们在PHP中编写的内容是
$person = array(
"firstname"=>"Smith",
"lastname"=>"Bach"
);
那么这是同一件事情,还是我的理解有误?
我正在学习 JavaScript 的基础知识,其中涉及到 对象
,我看到了这个例子...
JavaScript
var person = {
firstname : "Smith",
lastname : "Bach"
};
我们在PHP中编写的内容是
$person = array(
"firstname"=>"Smith",
"lastname"=>"Bach"
);
那么这是同一件事情,还是我的理解有误?
不,对象不仅仅是那样。
对象确实是一张地图/字典,但另外每个对象都会从另一个对象继承一些属性(键-值对)。那个其他的对象被称为原型。
例如:
var o = {
x: 1
};
console.log(o.x === undefined); // false, obviously
console.log(o.toString === undefined); // false, inherited from prototype
通常可以通过使用构造函数创建一个对象来设置原型:
var d = new Date();
console.log(d.hasOwnProperty('getYear')); // false, it's inherited
编辑:
这是使用构造函数制作原型的工作方式(这是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());
var o = {};
alert("toString" in o); // alerts "true"
ECMAScript 5具有定义对象属性的机制,使其成为不可变且不可迭代的,这有助于某些情况。但如果您想在对象中存储一个名为“toString”的属性,则仍然存在问题。
array
(数组和哈希映射混合在一个数据结构中)是一个糟糕而混乱的概念。你应该询问“它如何工作”,而不是“它与PHP中的xyz类似”。 ;) - duri