Home > Web Front-end > JS Tutorial > body text

JavaScript中对象property的读取和写入方法介绍_javascript技巧

WBOY
Release: 2016-05-16 16:23:09
Original
1437 people have browsed it

JavaScript中,可以通过点号操作符”.”或者中括号操作符”[]“来对对象的property进行读取和写入:


复制代码 代码如下:

var o = {x:1, y:2};
console.log(o.x);//1
console.log(o["y"]);//2
o.y = 7;
console.log(o["y"]);//7


值得注意的是,如果使用中括号操作符,则操作符内的值类型必须是string,或者能够转换成string的表达式:


复制代码 代码如下:

console.log(o[y]);//ReferenceError: y is not defined
var v = "y";
console.log(o[v]);//7


与Java语言不同的是,JavaScript中对象的property可以动态添加或删除。当对某个property进行赋值操作时,如果该property不存在,JavaScript会在对象中动态添加此property:


复制代码 代码如下:

o.z = 99;
console.log(o);//Object {x=1, y=7, z=99}

 

原型继承链中property的读取

 

JavaScript中所有的对象均有一个prototype原型对象,并从该原型对象中继承property;因此,JS中一个对象的property分成两大类:

1.对象自身所拥有的property(“Own Property”)。
2.从原型对象处继承而来的property。

当读取对象的property时,所遵循的规则如下:

1.从对象自身的property集合(“Own Property”)中搜索需要读取的property;如果可以搜索到,则直接读取该property并返回其值。
2.如果无法从对象自身的property集合(“Own Property”)中搜索到该property,那么则从对象的prototype原型链中继续进行搜索,直至搜索到该property并返回其值。
3.如果无法从对象自身的property集合(“Own Property”)中搜索到该property,也无法从对象的所有prototype对象中搜索到该property,则返回undefined。

原型继承链中property的写入

在对JavaScript对象的property进行写入时,所遵循的规则如下:

1.如果对象自身有该property,且该property可写,则将新值写入该property。如果该property只读,则报错。
2.如果对象自身没有该property,且其所有的prototype对象中也不存在该property,则将此property添加到该对象中。
3.如果对象自身没有该property,但其prototype对象中存在该property且可写,那么JS会在对象中新建这个property;也就是说,该对象覆写了其prototype对象中的这个property。prototype对象中此property值不变。
4.如果对象自身没有该property,但其prototype对象中存在该property且只读,则报错。
5.如果对象自身没有该property,但其prototype对象中存在该property的setter方法,那么JS会调用该prototype对象中的setter方法。值得注意的是,在运行setter方法时,如果涉及到变量赋值,那么赋值操作将作用在对象自身上,而prototype对象不会有任何改动。对于这一行为,可以理解为:对象从prototype处继承了setter函数并加以执行。

从上述规则中可以发现,如果对property的赋值操作成功,那么最后被修改的永远是对象自身,其prototype原型对象不会有任何改动。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!