JavaScript Advanced Programming (Third Edition) Learning Notes 6, 7 Chapter _javascript Tips

Source: Internet
Author: User
Tags hasownproperty

The 6th chapter, object-oriented programming

Object:

1, Data properties

Configurable, which indicates whether the attribute can be deleted by deleting the property, whether the attribute is modified, or whether the property can be modified to an accessor property, and the default is True

Enumerbale, which indicates whether the property can be accessed through for-in, default True

Writable, which indicates whether property values can be modified, default True

Value, data storage location, default undefined

Modify default attribute attribute: Object.defineproperty (), receives three parameters: Property object, property name, descriptor object, descriptor object attribute must be: Configurable, enumerable, writable, value

Cases:

var obj = {};
Object.defineproperty (obj, "name", {
writable:true,
value: "Nihao"

2, accessor properties

Configurable, which indicates whether the attribute can be deleted by deleting the property, whether the attribute is modified, or whether the property can be modified to an accessor property, and the default is True

Enumerbale, which indicates whether the property can be accessed through for-in, default True

Get, called when reading properties, default undefined

Set, called when writing properties, default undefined

Modification must pass Object.defineproperty ()

Cases:

var obj = {
_year:2004,
edition:1
}
object.defineproperty (book, year, {
get:function () {
Return This._year
},
set:function (newvalue) {
if (NewValue >) {
this._year = newvalue;
This.edition + = newvalue–2004;
}}
);
Book.year = 2005;

Define multiple attributes: Object.defineproperties (), receives two objects, one is to modify and add the property of the cashing, the second object property and the first object to modify or add the property one by one corresponding, supported browsers: IE9+,FIREFOX4+,SAFARI5 +,opera12+,chrome

Read properties: Object.getownpropertydescriptor (), receiving two parameters, the object of the property, to read the descriptor's property name, supported browsers: ie9+,firefox4+,safari5+,opera12+, Chrome

To create an object:

Factory mode:

function Createperson (name,age) {
var o = new Object ();
O.name = name;
O.age = age;
O.sayname = function () {
alert (this.name);
};
return o;
}
var person1 = Createperson ("G", 29); 

Constructor pattern:

function Person (name,age) {
this.name = name;
This.age = age;
This.sayname () = function () {
alert (this.name);}
;
}

Two modes of difference:

There is no need to display the creation object in the constructor pattern, assign a value directly to this, no return statement

The first letter of the constructor must be capitalized, and a new instance must be created using the the new operator

Prototype mode

Each function created has a prototype (prototype) attribute, which is a pointer to an object that contains properties and methods that can be shared by all instances of a particular type, in other words, prototype is the prototype object of the object created by the function, The advantage is that all instances can share the same properties and methods.

isPrototypeOf (), personal understanding is to be able to determine whether an instance of the prototype is the same as the current prototype

Cases:

Person.prototype.isPrototypeOf (Person1); True

Object.getprototypeof (), you can return the prototype of an instance, supported browsers Ie9+,firefox3.5+,safari5+,opera12+,chrome

Note: When accessing the object property name, a search is made, first in the instance object search, and not in the prototype object of the current object.

Note: An attribute in an instance that is the same as a property in a prototype object masks the properties of the prototype object, just as the previous one can be right.

hasOwnProperty () method to determine whether a property is from an instance, not from an instance, returns FALSE, otherwise returns true

When you call delete on an instance, only the property name on the instance is deleted and the stereotype's properties are not deleted

Cases:

function person () {
}
Person.prototype.name = "Nicholas";
Person.prototype.age =;
Person.prototype.sayName = function () {
alert (this.name);
}
var per1 = new Person ();
var per2 = new Person ();
Per1.name = "Greg";
alert (per1.name); "Greg" comes from instance
alert (per2.name);//"Nicholas"
delete per1.name;
alert (per1.name); "Nicholas" comes from the prototype
delete per1.name;

Note: the Object.getownpropertydescriptor () method can only be used for instance properties, and to obtain a prototype property descriptor, you must call this method directly on the prototype object

In operator: Returns true only if the property is in an instance object or in a prototype object

Cases:

Alert ("name" in person); True

Both in and hasownproperty can be used to determine whether the property exists in the prototype or in an instance

Object.keys () Method: Receives an object as an argument, returning a string array of all enumerable properties

Object.getownpropertynames () Method: Receives an object that returns an array of strings of all properties, whether or not an enumerable

Simpler prototype syntax:

Using the above method is too cumbersome, and more often uses the following methods: using Object literals

Person.prototype = {
name: ' Nicholas ',
age:29
sayname = function () {
alert (this.name);
}

However, this method, which overrides the entire prototype object, will cause the constructor property to point to the object instead of to the person, although instanceof will return the correct result. However, the object type cannot be determined by constructor.

var per = new person ();
Alert (per instanceof Object); True
alert (per instanceof person),//true
alert (per constructor Object);//true

If constructor is really important, you can set the following

Person.prototype = {
Constructor:person,
name: "Nicholas",
age:29
sayname = function () {
alert ( this.name);
}

The above notation sets the enumerable attribute of constructor to true, by default the native is false, and can be set using Object.defineproperty () in a compatible ECMAScript5 browser

Object.defineproperty (Person.prototype, "constructor", {
enumerable:false,
Value:person

Note: Rewriting the prototype object will sever the connection between the existing prototype and any previously existing object instances

Inheritance (more difficult, need to study carefully)

Using a prototype chain to implement

To override the superclass method, the code that adds the method to the stereotype should be placed after the replacement prototype,

Note: When inheriting through the prototype chain, the prototype method cannot be created using object literals, otherwise the prototype chain is rewritten

Borrowing constructors

Combined inheritance

Prototype inheritance, Object.creat (); receives two parameters: one is the object that is used as the prototype of the new object and (optionally) an object that defines additional attributes for the new object

Example: Object.creat (person,{name:{value: "Greg"});

Parasitic inheritance

Parasitic Modular Inheritance

The 7th chapter, the expression of function

How to create:

1, function declaration, can be a function of the declaration of Ascension, you can use the function of the statement before the function declaration

function Funname (ARG0,ARG1) {
//functions Body

2, function expression, can not be a function of ascension, that is, the function can not be used before the creation of functions, in this case, the creation of functions called anonymous functions, sometimes called the lambda function

var funname = function (ARG0,ARG1) {
//functions Body

In strict mode, you cannot use Arguments.callee to implement recursion, and you can implement recursion in the following ways:

var factorial = (function f (num) {
if (num <= 1) {return
1;
} else{return
num * f (num-1);
}

Closure (difficulty is also not small)

Closures are functions that have access to variables in the scope of another function, closures, and also a function

A common way to create closures is to create another function inside one function

Closures can only take the last value that contains a function, that is, any variable in the external function. The following example can clearly explain the problem

Cases:

function Createfuncrions () {
var result = new Array ();
for (var i = 0;i < 10;i++) {
Result[i] = function () {return
i;
}
}
return result;
}
var re = createfuncrions ();

Each function returns 10 instead of returning the corresponding index value as expected, because the Createfuncrions function finally returns when i = 10, where each function references the same object that holds the variable I, so within each function I is 10, You can force closures to return the desired effect by using the following methods:

function Createfuncrions () {
var result = new Array ();
for (var i = 0;i < 10;i++) {
Result[i] = function (num) {return
function () {return
num;
} (i);
}
return result;
}
var re = createfuncrions ();

Each will return its own index value

Impersonation block-level scopes

Use anonymous functions to mimic block-level scopes:

(function () {
alert ("test");//block-level scope, without parentheses the function will be wrapped with an error

The obvious disadvantage of using closures and private variables is that they look for more than one level in the scope chain and, to some extent, affect the lookup speed

A variable defined in a function can be called a private variable to some extent, and a function can simulate a private variable, a static private variable

Enhanced Module Mode:

var singleton = function () {
//private arg and private method
var privatevariable = ten;
function Privatefunction () {return
false;
}
Create obj
var obj = new Object ();
Obj.publicproperty = true;
Obj.publicfunction = function () {
privatevariable + +;
return privatefunction ();
};
return obj;
} ();
Alert (typeof Singleton);
alert (singleton.publicproperty);
Alert (Singleton.publicfunction ());

The above content is small series to introduce the JavaScript Advanced Program Design (third edition) study notes 6, 7 chapters, hope to help everyone!

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.