Javascript secret garden-object, prototype

Source: Internet
Author: User
Tags mozilla developer network
ArticleDirectory
    • About authors (the authors)
    • Contributors)
    • License)
    • Chinese Translation)
    • Object as data type (objects as a data type)
    • Accessing Properties)
    • Deleting Properties)
    • Property name syntax (notation of keys)
    • Property Lookup)
    • The prototype Property)
    • Performance)
    • Extension of native prototypes)
    • Conclusion (In conclusion)

Http://bonsaiden.github.com/JavaScript-Garden/zh/#object.forinloop

Introduction (intro)

Javascript Secret GardenIt is a constantly updated document that focuses on some odd JavaScript usage. It provides suggestions on how to avoid common errors, hard-to-find problems, performance problems, and poor practices. Beginners can learn more about the language features of JavaScript.

Javascript Secret GardenNoIt is used to teach you JavaScript. To better understand the content of this article, you need to learn the basic knowledge of Javascript in advance. There are a series of excellent JavaScript learning guides in the Mozilla Developer Network.

About authors (the authors)

This article is written by two stack overflow users, Ivo Wetzel and Zhang Yi Jiang ).

Contributors)
    • Caio Rom? O (spelling check)
    • Andreas blixt (Language correction)
License)

The javascript garden was released under the MIT License Agreement and stored in Open SourceCommunityGitHub. If you find an error or incorrect typing, file an issue or pull request. You can also find us in the Javascript room of the stack overflow chat room.

Chinese Translation)
    • Javascript garden-original
    • Javascript garden-Chinese Translation
    • Translated by: sanshenshi

This Chinese translation is original on sanshangshi, and is the first in the blog Park. For more information, see the source.

Object (objects) # top

All variables in JavaScript are objects, except for twoNullAndUndefined.

?
1 <Code>False. Tostring ()// 'False' <br> [1, 2, 3]. tostring (); // '1, 2,3 '<br> function Foo () {}< br> Foo. bar = 1; <br> Foo. bar; // 1 <br> </code>

A common misunderstanding is that the literal value of a number (literal) is not an object. This is because of an error in the Javascript parser, which triesPoint OperatorResolved to a part of the floating-point numeric value.

?
1 <Code> 2. tostring ();// Error: syntaxerror <br> </code>

There are many workways to make the literal value of A number look like an object.

?
1 <Code> 2. tostring ();// The second vertex can be resolved properly <br> 2. tostring (); // note the space before the dot <br> (2 ). tostring (); // 2 is calculated first <br> </code>
Object as data type (objects as a data type)

Javascript objects can be usedHash tableUsed to save the correspondence between the named key and value.

Use the literal Syntax of an object-{}-You can create a simple object. This newly created object is fromObject. PrototypeThere are no custom attributes.

?
1 <Code>VaR Foo = {};// An empty object <br> // a new object with a custom property 'test' with a value of 12 <br> var bar = {test: 12 }; <br> </code>
Accessing Properties)

There are two ways to access the attributes of an object, the dot operator or the brackets operator.

?
1 <Code>VaR Foo = {Name:'Kitten'} <Br> Foo. Name;// Kitten <br> Foo ['name']; // kitten <br> var get = 'name'; <br> Foo [get]; // kitten <br> foo.1234; // syntaxerror <br> Foo ['1234']; // Works <br> </code>

The two syntaxes are equivalent, but the brackets operator is still valid in the following two cases-dynamic attribute setting-attribute name is not a valid variable name (note: for example, the property name contains spaces or the property name is a JS keyword)

Deleting Properties)

The only way to delete an attribute is to useDeleteOperator; set the attributeUndefinedOrNullThe attribute cannot be deleted.OnlyIs to remove the association between attributes and values.

?
1 <Code> VaR OBJ = {<br> bar: 1, <br> FOO: 2, <br> Baz: 3 <br >}; <br> obj. bar = undefined; <br> obj. foo = Null ; <Br> Delete OBJ. Baz; <br> For ( VaR I In OBJ) {<br> If (Obj. hasownproperty (I) {<br> console. Log (I, '' + OBJ [I]); <br >}< BR >}< br> </code>

The above output results include:Bar undefinedAndFoo null-OnlyBazDeleted from the output.

Property name syntax (notation of keys) ?
1 <Code>VaR Test = {<br>'Case':'I am a keyword so I must be notated as a string', <Br>Delete:'I am a keyword too so me' // Error: syntaxerror <br >}; <br> </code>

Object attribute names can be declared using strings or common characters. However, due to another incorrect design of the Javascript parser, the second declaration method above will be thrown before ecmascript 5Syntaxerror.

The cause of this error is:DeleteIs a javascript LanguageKeywordsTherefore, you must useString Literal ValueDeclaration method.

Prototype # top

JavaScript does not contain the traditional class inheritance model, but usesPrototypicalPrototype model.

Although this is often mentioned as a disadvantage of JavaScript, prototype-based inheritance models are more powerful than traditional class inheritance models. It is easy to implement the traditional class inheritance model, but it is much more difficult to implement prototype inheritance in JavaScript. (It is for example fairly trivial to build a classic model on top of it, while the other way around is a far more difficult task .)

Since Javascript is the only language widely used based on prototype inheritance, it takes some time to understand the differences between the two inheritance modes.

The first difference is that JavaScript usesPrototype chain.

Note:Easy to useBar. Prototype = Foo. PrototypeTwo objects will be shared.Same. Therefore, changing the prototype of any object affects the prototype of another object. In most cases, this is not the expected result.

?
1 <Code> Function Foo () {<br> This . Value = 42; <br >}< br> Foo. Prototype = {<br> method: Function () {}< BR >}; <br> Function Bar () {}< br> <br> // set the prototype attribute of bar to the Instance Object of Foo
bar. prototype = new Foo ();
bar. prototype. foo = 'Hello world';
// modify bar. prototype. constructor is the bar itself
bar. prototype. constructor = bar;
var test = new bar () // create a new instance of bar
// prototype chain
test [Bar instance]
bar. prototype [Foo instance]
{FOO: 'Hello world'}
Foo. prototype
{method :...};
object. prototype
{tostring :... /* etc. */};

In the above example,TestObject slaveBar. PrototypeAndFoo. PrototypeInherited; therefore, whether it can accessFooPrototype MethodMethod. But it cannot accessFooInstance attributesValueBecause this attribute isFoo. (But it will not have access to the propertyValueOfFooInstance, since that property gets defined in the constructorofFoo. But this constructor has to be called explicitly .)

(Translator's note: I think this description is incorrect, and test. value is accessible. Because when bar. Prototype = new Foo (); is set,ValueIt becomes an attribute of bar. prototype. If you have different opinions, you can go to my blog to comment .)

Note: NoUseBar. Prototype = fooBecause this will not be executedFooIs directed to the FunctionFoo. Therefore, the prototype chain will be traced backFunction. PrototypeInsteadFoo. Prototype, SoMethodIt will not be on the bar prototype chain.

Property Lookup)

When you look for the attributes of an object, JavaScript willUpTraverse the prototype chain until the property of the given name is found.

Go to the top of the prototype chain-that isObject. Prototype-If the specified attribute is still not found, undefined is returned.

The prototype Property)

When a prototype property is used to create a prototype chainAnyType value to it (prototype ). However, operations that grant the atomic type to prototype are ignored.

?
1 <Code>Function Foo () {}< br> Foo. Prototype = 1;// No effect <br> </code>

Assign an object to prototype. As shown in the preceding example, the prototype chain is dynamically created.

Performance)

If an attribute is at the top of the prototype chain, the query time will be adversely affected. In particular, an attempt to obtain an attribute that does not exist will traverse the entire prototype chain.

In addition, when the for-in loop is used to traverse the attributes of an objectAllAll attributes will be accessed.

Extension of native prototypes)

An error feature is frequently used, that is, expansionObject. PrototypeOr other built-in prototype objects.

This technology is called Monkey patching and will destroyEncapsulation. Although it is widely used in some JS class libraries such as prototype, I still do not consider adding someNon-standardIs a good idea.

Extended built-in typesUniqueThe reason is to be consistent with the new JavaScript, suchArray. foreach. (Note: This is a common method in the programming field, called backport, that is, to add new patches to the old version .) TheOnlyGood reason for extending a built-in prototype is to backport the features of newer Javascript Engines; for example,Array. foreach.

Conclusion (In conclusion)

Before writing complex JavaScript applications, we fully understand that the method of prototype chain inheritance isProgramEmployeeRequired. Beware of performance problems caused by too long prototype chains and know how to improve performance by shortening prototype chains. Further, absoluteNoExtended built-in prototype unless it is intended to be compatible with the new JavaScript Engine.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.