JavaScript Object-oriented essentials (i)

Source: Internet
Author: User
Tags access properties

Several features of traditional object-oriented languages: encapsulation, inheritance, polymorphism, not applicable in JavaScript. JavaScript's weak-type features allow you to accomplish the same tasks with less code than in other languages. No need to design classes in advance and then encode them. Need an object with a field? You can create them anytime, anywhere. Nicholas
C.zakas's book, "JavaScript Object-oriented essentials," tells us how to create objects, define our own types, use inheritance and a variety of other operations to get the most out of objects. In short, a more comprehensive understanding and use of all of JavaScript.

One, primitive type and reference type 1. What is a type

JavaScript does not have a class concept, but there are two types: primitive type and reference type .
The original type is saved as a simple data value, and the reference type is saved as an object, essentially a reference to a memory location.

varnewObject();

A variable does not actually contain an instance of an object, but rather a pointer (or reference) to the location of the actual object in memory . This is a fundamental difference between the object and the original value. The original values are stored directly in the variable.
attached : about variables See "variables, scopes, and memory issues"

2. Instantiation of built-in types

Example: Object literal form

var obj1 = {};varnewObject();

Object literals, the JavaScript engine does a pretty similar job behind new Object() it, except that no constructor is called.
Example: Regular expression literal form

var/^\d+$/g;varnewRegExp("^\\d+$""g"// "/^\d+$/g"reg2.source;     // "^\d+$"

Use the literal next form to create the regular, without worrying about the escape character in the string. If you use the RegExp constructor, the parameters of the incoming pattern are a string that needs to be transferred.

3. Accessing properties

Example: properties that treat special characters

var obj = {    "ab":"yes",    "a$b":"yes",    "abc":"yes"};obj.ab;     //"yes"obj["a$b"];    //"yes""abc";obj[name];  //"yes"

The brackets can handle dynamically determining which property to access and access properties that contain special characters , while others are roughly the same as "dot".

4. Identifying Reference Types

The discriminant reference type uses the instanceof operator.
Example: Arrays

ArrayinstanceofArray

You need to be aware of the judgments between different frameworks. See, "Advanced JavaScript tips-Safe type detection"

5. Original Package Type

Example: Automatic creation of basic wrapper types

var"string"instanceofString// falsenewString("string"instanceofString// true

A temporary object that is created only when the value is read and then destroyed immediately. The instanceof operator does not actually read anything.

Second, function

Functions are also objects. The attribute that makes a function different from other objects is that it has attributes inside it [[Call]] . This property cannot be accessed through code but defines the behavior when code executes. ECMAScript defines the typeof operator to [[Call]] return "function" to any object that has attributes.
Example: determining whether a function

typeoffunction(){};    // "function"typeof /\./;    // "object"

Note : Some browsers used to include the [call] property in a regular expression, causing it to be incorrectly identified as a function.

1. Function Promotion

The declaration itself is promoted, and the assignment, including the assignment of a function expression, is not lifted; The following function declaration can overwrite the previous.
Example: function Promotion

a();    "a..."b();    notfunction(…)function a(){    console.log("a");};function a(){    console.log("a..."function(){    console.log("b");}
2. Change this

Example: Obj has the Sayname () method

var obj = {    "obj",    function(age){        console.log("my name is:"this",age: " + age);    }}

(1) Call () method

var"call"25// my name is:call,age: 25

(2) Apply () method

var"apply"};obj.sayName.apply(obj2, [25]);  // my name is:apply,age: 25

(3) Bind () method

var"bind"};var sayName = obj.sayName.bind(obj3);sayName(25);    // my name is:bind,age: 25

Note : call() apply() Execution immediately bind() returns a function that is not immediately executed.
About functions. See, "JavaScript promotion (JavaScript you don't know)", "function expression"

Third, understand the object 1. Defining properties

When a property is first added to an object, JavaScript invokes an internal method called [[Put]] on the object, and when an existing property is given a new value, a method named is called [[Set]] .

"lg";     // 调用[[Put]]"ligang"; // 调用[[Set]]
2. Attribute detection
if(person.age){    //do something with age}

The value is a null, undefined, 0, False, NaN , or empty string when evaluated as false. Because an object property can contain these false values, the above example may lead to an incorrect assumption. Note that this problem is also present in the short-circuit &&.

ifin person){    //do something with age}

inThe operator is the best way to probe for the existence of an attribute in an object and does not evaluate the value of the property.

3. Attribute types

There are two types of properties: Data Properties and accessor properties .
If you only need to save your data, there's usually no reason to use accessor properties – just use the property itself. But when you want the assignment to trigger some behavior or read a value that needs to be calculated by calculating the desired return, the accessor property is useful.

varperson = {_name:"LG"};object.defineproperty (Person,"Name", {Get: function(){Console.log ("My name is:"+ This. _name);return  This. _name; },Set: function(name){         This. _name ="Aixinjueluo"+ Name; }});//equivalentvarperson = {_name:"LG",GetName () {Console.log ("My name is:"+ This. _name);return  This. _name; },SetName (name) { This. _name ="Aixinjueluo"+ Name; }};p Erson.name;//My name IS:LGPerson.name ="Ligang";p Erson.name;//My name is: Aixinjueluo Ligang

Vue formally Object.defineProperty() listens to the property and notifies the processing.
Note : Creating an attribute with both data characteristics and accessor characteristics will get an error.

JavaScript Object-oriented essentials (i)

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.