JavaScript Object只是一个关联数组吗? [英] Is JavaScript Object nothing but an associative array?
问题描述
好的,我正在浏览JavaScript的基础知识,我正在学习对象
我遇到过这个例子......
Ok am just going through basics of JavaScript and I was learning objects
where I came across this example...
JavaScript
JavaScript
var person = {
firstname : "Smith",
lastname : "Bach"
};
我们用PHP写的是
$person = array(
"firstname"=>"Smith",
"lastname"=>"Bach"
);
这是同样的事情,或者在理解这个概念时犯了错误?
So is this the same thing or am making a mistake in understanding the concept?
推荐答案
不,对象不止于此。
对象确实是地图/字典,但另外每个对象都从另一个对象继承了一些属性(键值对)。另一个对象称为原型。
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.
例如:
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
编辑:
以下是原型如何使用构造函数(它是一个在JS中进行OOP的方式):
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());
这篇关于JavaScript Object只是一个关联数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!