Introduction to JavaScript Prototypes

Source: Internet
Author: User

Prototype and prototype chain prototype basic concept
function Person () {    this.name = 'John';}var person = new Person();Person.prototype.say = function() {    console.log('Hello,' + this.name);};person.say();//Hello,John

The code is very simple, and the person prototype object defines a common say method, although this occurs after the instance is constructed, but because the prototype method has been declared before the call, this method is found on its own prototype when the instance itself does not have this say method.

Prototype chain
function Foo() {    this.value = 42;}Foo.prototype = {    method: function() {}};function Bar() {}// 设置Bar的prototype属性为Foo的实例对象Bar.prototype = new Foo();Bar.prototype.foo = 'Hello World';// 修正Bar.prototype.constructor为Bar本身Bar.prototype.constructor = Bar;var test = new Bar() // 创建Bar的一个新实例// 原型链test [Bar的实例]    Bar.prototype [Foo的实例]         { foo: 'Hello World' }        Foo.prototype            {method: ...};            Object.prototype                {toString: ... /* etc. */};

In the example above, the test object inherits from Bar.prototype, so it can access the Bar's prototype method, while Bar.prototypefoo the instance object of Foo, and can access the prototype method of Foo. It is also able to access the Foo instance property value. It is important to note that the new bar () does not create an instance of Foo, but instead reuses the instance on its prototype, so all Bar instances share the same Value property.

Property Lookup

When looking up a property of an object, JavaScript traverses the prototype chain up until it finds the property of the given name, until the lookup reaches the top of the prototype chain-that is, object.prototype-but still does not find the specified property, it returns undefined, Let's look at an example:

 function foo() {     this.add = function (x, y) {         return x + y;     } } foo.prototype.add = function (x, y) {     return x + y + 10; } Object.prototype.subtract = function (x, y) {     return x - y; } var f = new foo(); alert(f.add(1, 2)); //结果是3,而不是13 alert(f.subtract(1, 2)); //结果是-1

Running through the code, we found that subtract is installing what we call upward lookup to get results, but the Add method is a little different, which is what I want to emphasize, is that the property in the search is the first to find their own properties, if not to find the prototype, no, then go up, has been plugged into the prototype of object, so at some level, the efficiency is also a problem when traversing properties with a for in statement.

Another thing we need to note is that the prototype of the basic constructor in JS is non-rewritable, cannot be deleted, not visible;

Object.getOwnPropertyDescriptor(Number, 'prototype');// Object {value: Number, writable: false, enumerable: false, configurable: false};
hasOwnProperty function:

hasOwnProperty is a way of object.prototype, it's a good thing, he can tell if an object contains custom attributes, not properties on the prototype chain,

// 修改Object.prototypeObject.prototype.bar = 1; var foo = {goo: undefined};foo.bar; // 1'bar' in foo; // truefoo.hasOwnProperty('bar'); // falsefoo.hasOwnProperty('goo'); // true

Use hasOwnProperty can give correct and expected results, which is useful when traversing the properties of an object.

Objects in the search for properties, first from the self-lookup, not found in the prototype chain to find, layer up once found on the return, until the search is Object.protype not found to return to undefined.
You can experience the following results, it is recommended to do some of JS in the constructor and function types of prototype chain, thoroughly understand their relationship.

Function.toString === Object.toString                       // trueFunction.prototype.toString === Object.toString             // trueFunction.prototype.__proto__ === Object.prototype           // tureFunction.prototype.toString === Object.prototype.toString   // false

hasOwnProperty is the recommended method when checking for the existence of an attribute on an object. It is also recommended to always use the hasOwnProperty method when traversing an object using the for in loop, which avoids the interference caused by the prototype object extension, let's take a look at the example:

// 修改 Object.prototypeObject.prototype.bar = 1;var foo = {moo: 2};for(var i in foo) {    console.log(i); // 输出两个属性:bar 和 moo}

We have no way to change for in the behavior of the statement, so we want to filter the results can use hasOwnProperty the method, the code is as follows:

// foo 变量是上例中的for(var i in foo) {    if (foo.hasOwnProperty(i)) {        console.log(i);    }}

This version of the code is the only correct notation. Since we used the hasownproperty, we only output moo this time. If you do not use hasOwnProperty,
You can also use Object.key () to get a list of the properties and methods of the target, resulting in an array of properties that are on the target object, without its prototype and its own non-enumerable properties, which can be used with mates for finer Object.getOwnPropertyNames() results hasOwnProperty() .

Summary: It is recommended to use hasOwnProperty, do not make any assumptions about the environment in which the code runs, and do not assume that native objects have been extended.

Summarize

Prototypes greatly enrich our development code, but in the ordinary use of the process please be sure to pay attention to the above mentioned considerations.

    1. A lookup rule for object properties, and a mask between attributes on the prototype chain.
    2. Deep understanding hasOwnProperty() , for in mechanism, Object.keys() .
    3. inOperators have the ability to traverse to the top of the prototype chain, and can be obtained from objects and the non-enumerable attributes on the prototype chain true , so for in that we traverse the method on the prototype chain.
    4. Object.getOwnPropertyDescriptor()can help us to understand the properties on the object more carefully.
    5. It also involves Object.defineProperty() methods that can be used to define a property on an object very carefully, to accept three parameters, an object, a property name (string), a property descriptor (object), and a Object.defineProperties() similar one, except that it accepts 2 parameters, an object to be defined by the property (o Bject), property describes the collection props (object), which can define multiple properties at once.

Introduction to JavaScript Prototypes

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.