JavaScript Object-oriented Essentials (ii)

Source: Internet
Author: User
Tags define local hasownproperty

Iv. Constructors and prototype objects 1. constructor function

Constructors are functions that are called when you create an object with new. The advantage of using constructors is that all objects created with the same constructor have the same properties and methods.

function Person(){}varnew// trueinstanceof Person);      // true

You can use constructors to examine the type of an object, but it is still recommended to use instanceof to check the object type. Because constructor properties can be overwritten, they are not necessarily completely accurate.
Example: Constructors return objects

function Foo(){    this"foo";    return"hhh"};}varnew Foo();f.name;         // hhhf.constructor;  // Object

Example: Constructor returns the original type

function Too(){    this"too";    return"hhh";}varnew Too();t.name;         // toot.constructor;  // Too

The constructor displays the call return:

    • If the returned value is an object, it will replace the newly created object instance returned;
    • If the returned value is an original type, it is ignored and the newly created object instance is returned.
2. Prototype objects

Please refer to: "Detailed prototype and proto difference"

3. Change the Prototype object

[[Prototype]]The property simply contains a pointer to the prototype object, not a copy, and any changes to the prototype object are immediately reflected on all object instances that reference it.
Example: Extending a Prototype object

function Person(){}var p = new Person();p.sayHi();  //  notfunction(…)function(){    console.log("hi");};p.sayHi();  "hi"

Note : When used on an object Object.seal() or Object.freeze() when it is purely an action object's own property, you can extend these object instances by adding properties to the prototype.
Example: Freezing an Object

function Person(name){}varnew Person();Object"ligang"function(){    console.log("hi");};console.log(p.name);    // undefinedp.sayHi();  // "hi"

For objects, see: "Object-oriented Programming", "Advanced JavaScript tips-Tamper-resistant objects"

V. Inheritance

JavaScript's built-in inheritance methods are called prototype object chains, also known as prototype object inheritance. When an object is [[Prototype]] set to another object, a chain of prototype objects is created between the two objects.

1. Object.prototype

All objects inherit from Object.prototype .

Method Description
hasOwnProperty () Checks if there is a property for a given name
propertyIsEnumerable () Checks if an own property can be enumerated
isPrototypeOf () Checks whether an object is a prototype object for another object
ValueOf () Returns the value representation of an object
ToString () Returns a string representation of an object

The above 5 methods appear in all objects through inheritance.
(1) valueOf ()
valueOf()By default, the object instance itself is returned, and you can define your own valueOf() method, which does not change the behavior of the operator when defined, and only defines the value used by the operator's default behavior.
(2) toString ()
Once valueOf() a reference is returned instead of the original value, the call is rolled back toString() .
Example:

varObj1 = {valueOf: function(){        return "ValueOf"; }, ToString: function(){        return "ToString"; }}varObj2 = {valueOf: function(){        return{Name:"haha"}; }, ToString: function(){        return "ToString"; }}obj1 +"";//"ValueOf"Obj2 +"";//"toString"
2. Modify Object.prototype

When Object.prototype adding a method, the default is enumerable, which means that it can appear in the for-in loop. Douglas Crockford (the father of JavaScript) is recommended to always be used in for-in loops hasOwnProperty() .

varempty"LIGANG";for(varempty){    console.log(prop);      // 会输出:myName}for(varempty){    if(empty.hasOwnProperty(prop)){        console.log(prop);  // 无任何内容输出    }}

Therefore, in the for-in operation, the best way is to increase hasOwnProperty() judgment, and at this time, do not modify Object.prototype .

3. Object inheritance

Object inheritance is the simplest type of inheritance, and what you need to do is specify which object is the new object [[Prototype]] .
In the process of creating an object, the literal form is implicitly specified Object.prototype for it [[Prototype]] , or it can be displayed in a Object.create() way specified.

var obj1 = {};varObject.create(Object.prototype, {});

Object.create()method, the first parameter is an object that needs to be set as a new object [[Prototype]] , and the second parameter is an attribute description object, formatted with Object.defineProperties()
Example: Prototype object chain (inheritance)

var person = {    "person",    function(){        console.log(this.name);    }};varObject.create(person, {    name: {        true,        true,        "ligang",        true    }});     


The end is usually Object.prototype one [[prototype]] of which is set to null.
Example: Empty Object

var obj1 = {};varObject.create(null);"toString"in// true"toString"in// false

Obj2 objects that do not have a chain of prototype objects. is completely a whiteboard without any pre-defined attributes, making it a perfect hash container.

4. Constructor inheritance

All object instances of the constructor share the same prototype object, so they inherit from the object, but cannot inherit their own properties with a prototype object.

function Person(name){    this// 私有属性function(){  // 共用方法    console.log(this.name);};varnew Person("ligang");varnew Person("camile");

P1,P2 are instances of the constructor person that share the Person.prototype prototype object. But its own property name cannot be inherited by a prototype object.
Summary : Own properties/methods through the constructor definition, a common attribute/method through the Prototype object Inheritance!!!

Vi. Object mode

Although JavaScript does not have a formal concept of private (local) attributes (let syntax appears in ES6, you can define local variables), you can create data or functions that can be accessed only within an object. Use module mode to hide data from the outside world, or you can use the Call function expression (Iife) to define local variables and functions that can be accessed only by newly created objects.

1. Private members and privileged members
var obj = (function(){    // 私有变量    var"ligang";    return {        // 公共的方法和属性        function(){            return author;        }    // undefined// "ligang"

The above function only exists in the instant that is called and is destroyed as soon as it executes.

// 上述示例的等价写法var obj = (function(){    // 私有变量    var"ligang";    varfunction(){        return author;    };    return {        // 公共的方法和属性        getAuthor: getAuthor    };}());
2. Mixing

Mixed to copy an attribute from one object to another, allowing the recipient to gain functionality without inheriting the provider. Unlike inheritance, mixing makes it impossible to check the source of a property after it has been created. If you want to get more powerful features and need to know where the feature comes from, inheritance is the first choice!

function mixin(des, src){    for(varin src){        if(src.hasOwnProperty(prop)){            des[prop] = src[prop];        }    }    return des;}

Note the above way, not the deep copy!
The odd dance group offers deep copy: Https://github.com/75team/mixin.js

var a = {x:{y:1, z:3}};mixin(a, {x:{y:2}, z:2function(a,b){    try{        returnarguments.callee)    }catch(ex){        return b    }});

Equivalent tojQuery.extend(true, a, {x:{y:2}, z:2});

3. Scope-Safe constructors
function Person(name){    this.name = name;}varnew Person("ligang");var p2 = Person("camile"instanceof// trueinstanceof// false

A scope-safe constructor is a constructor that can be called to generate a new object instance without using new. Its this will already point to the instance of the custom type at the beginning of the constructor execution. Of course, you can determine the behavior of the constructor based on whether or not new is used.

function Person(name){    if(thisinstanceof Person){        this.name = name;    }else {        returnnew Person(name);    }}var p = Person("ligang"instanceof// true

Many of the built-in constructors, such as array, regexp do not need new to work, because they were designed with a scope-safe constructor.

JavaScript Object-oriented Essentials (ii)

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.