JS object-oriented (3) Object class, static attributes, closures, private attributes, use of call and apply, inherited three implementation methods, objectapply

Source: Internet
Author: User
Tags hasownproperty

JS object-oriented (3) Object class, static attributes, closures, private attributes, use of call and apply, inherited three implementation methods, objectapply

1. Object Class

In JS, an Object is the base class of all classes. When you use an Object class to create a custom Object, you do not need to define Constructors (constructor, prototype, hasOwnProperty (property ))

var per = new Object();per.name = 'zhangsan';per.age = ;alert(per.name + per.age);

We want to get an Object variable in the program, as long as we can store a large amount of data, we can consider using the Object class. The Object class avoids the definition of the constructor. Another common property in the Object class: hasOwnProperty

Var per = new Object (); per. name = 'hangsan'; per. age =; if per. hasOwnProperty ('email ') {alert ('with email');} else {alert ('without email ');}

2. Static attributes

In some object-oriented languages, you can use the static keyword to define static attributes or static methods of the class. In JS, you can simulate the class.

Syntax:

Class Name. attribute name

Class Name. Property = function (){}

function Person(){}Person.count = ;var p = new Person();Person.count++;var p = new Person();Person.count++;var p = new Person();Person.count++;alert(Person.count);

Add static attributes and static methods:

Function Person () {Person. count ++; // Static Property Person. getCount = function () {// static method alert ('current total use' + Person. count + 'personal ');} Person. count =; var p = new Person (); Person. getCount ();

3. Closure

Concept: A closure refers to an expression (usually a function) with many variables and an environment bound to these variables. Therefore, these variables are part of the expression.

Raise a question:

Function display () {var I =;} display (); // here, you want to access the local variable I

In the global environment, the local variable I cannot be accessed because the scope is different. Moreover, after the display function is executed, the local variable I will be recycled. Function of the closure: "accessing local variables" and "Preventing memory occupied by variables from being released"

// Example function fn () {alert ('hello');} return fn; // return the first address of the fn function} var test = fn (); // test also points to the first address of the fn function test ();

In example 1, we know that the variable can point to the first address of the function, and the function can return the first address of another function.

// Example function fn () {var I =; function fn () {alert (I);} return fn; // return the first address of the fn function} var test = fn (); // test also points to the first address of the fn function test ();

In Example 2, we know that the memory of the local variable I will not be recycled by using a denial function to include variable I.

// Example function fn () {var I =; function fn () {alert (I ++);} return fn; // return the first address of the fn function} var test = fn (); // test also points to the first address of the fn function test ();

In Example 3, because the I memory will never be recycled, the I value is + 1 each time fn2 is called. The running result is pop-up 10, pop-up 11, and pop-up 12.

Principle of closure: In Example 3, there are three scopes: global scope, fn1 scope, and fn2 scope. There is test = fn1 () in the global scope. In fact, this sentence is equivalent to test = fn2. In the fn1 scope, there are var I = 10 and return fn2, and in the fn2 scope, there is alert (I ++ ). When test = fn1 () is executed under the global scope, test points to the fn2 scope. At this time, I under the fn2 scope is caught by the global scope. According to the law of the scope chain, I is not defined in fn2, So I in fn2 is located in the upper scope and var I = 10 in fn1 scope. Therefore, the global test hooks the I of fn2, and the I of fn2 hooks the I of fn1, so the fn1 will not be recycled after it is completed.

4. Private attributes

In the object-oriented thinking, for some sensitive members who do not want to disclose them, they can be defined as private members. In JavaScript, this function can be simulated.

Syntax:

function Person(p_name){var name = p_name;this.age}

Var: Private

This: Public

function Person(p_name,p_age){this.name = p_name;var age = p_age;}var p = new Person('zhangsan',);alert(p.name);alert(p.age);

In the above example, we want to use var to represent private member attributes. However, after the Person constructor is executed, age will be recycled and cannot be used as a member attribute.

function Person(p_name,p_age){this.name = p_name;var age = p_age;this.setAge=function(a){age = a;}this.getAge=function(){return(age);}}var p = new Person('zhangsan',);p.setAge();alert(p.getAge());

This. setAge and this. getAge use the local variable age, So age is not recycled.

If only the set method is available, this attribute is only written.

If only the get method is available, this attribute is read-only.

5. Use of call and apply

Call and apply functions: Use the specified object to call the current function. The call and apply functions are the same, but the syntax is slightly different.

Syntax:

Call ([thisObj [, arg1 [, arg2 [, argN])

First parameter: Who will this point to during function execution?

The following parameters:

Apply ([thisObj [, argArray])

First parameter: Who will this point to during function execution?

Second parameter: array, indicating the parameter set

In js, functions can be called in the following ways:

Person (); // this in Person points to windowvar p = new Person (); // this in Person points to upper. person (); // this in Person points to perfunction Person (p_name, p_age) {this. name = p_name; this. age = p_age;} function speak () {alert (this. name + this. age);} var p = new Person ('hangsan',); // speak (); this calls this to point to window // p. the speak (); p object does not have the speak attribute.

Use call and apply to call

function Person(p_name,p_age){this.name = p_name;this.age = p_age;}function speak(){alert(this.name + this.age);}var p = new Person('zhangsan',);speak.call(p);speak.apply(p);

Call and apply do two things during execution: 1) point this inside the function to the first parameter. 2) call the function.

In addition, the problem can be solved as follows:

P1.say = speak;

P1.say ();

This solution is essentially different from the above solution:

The above solution is to directly call the speak function, but the point of this inside the function changes.

The following solution adds attributes to the p1 object, and the volume of the p1 object increases.

Example:

<Script> function fn () {this. style. color = 'red';} function fn () {this. style. fontSize = 'px ';} window. onload = function () {document. getElementById ('btn '). onclick = function () {var div = document. getElementById ('div '); fn. call (div); fn. apply (div );};}; </script> <div id = 'div '> hello javascript </div> <input type = 'button 'id = 'btn' value = 'OK'>

6. Three Methods of Inheritance

Concept: In some object-oriented languages, one class (subclass) can be used to inherit from another class (parent class), and The subclass can have attributes and methods of the parent class, this function can be simulated in js.

Three methods:

First: extend the Object Method

Object. prototype. method = function (parent class Object) {for (var I in parent class Object) {this [I] = parent class Object [I] ;}};

Example:

Object. prototype. ext = function (parObject) {// cyclically traverse all attributes of the parent class object for (var I in parObject) {// Add this traversal property to the subclass object // its value is the property value of this property of the parent class object. this [I] = parObject [I];} function Person (p_name, p_age) {this. name = p_name; this. age = p_age; this. speak = function () {alert (this. name + this. age) ;}} function Student (p_no) {this. no = p_no; this. say = function () {alert (this. no + this. name_this.age) ;}} var stu = new Student (); stu. ext (new Person ('xiaoqiang ',); stu. speak (); stu. say ();

Method 2: call and apply

Syntax:

Parent class constructor. call (this ,.......);

function Person(p_name,p_age){this.name=p_name;this.age=p_age;this.speak=function(){alert(this.name+this.age);}}function Student(p_no,p_name,p_age){this.no=p_no;this.say=function(){alert(this.name+this.age+this.no);}Person.call(this,p_name,p_age);}var stu = new Student(,'zhagsan',);stu.speak();stu.say();

Third: Prototype inheritance

Syntax:

Subclass. prototype = new parent class ();

function Person(p_name,p_age){this.name=p_name;this.age=p_age;this.speak=function(){alert(this.name+this.age);}}function Student(p_no){this.no=p_no;this.say=function(){alert(this.name+this.age+this.no);}}Student.prototype = new Person('wangwu',);var stu = new Student();stu.speak();stu.say();

The above content introduces the Object class, static attribute, closure, private attribute, call and apply of JS object-oriented (3), and inheritance methods, hope to help you!

Articles you may be interested in:
  • JS object-oriented, prototype, call (), apply ()
  • Js apply/call/caller/callee/bind usage and Difference Analysis
  • Object Usage Analysis of JS Object-Oriented Programming
  • Analysis on JS Object-Oriented Programming
  • JS object-oriented basic explanation (factory mode, constructor mode, prototype mode, hybrid mode, dynamic prototype mode)
  • Comparison and Analysis of call, apply, and bind usage in javascript
  • Usage of call (), apply (), and bind () in javascript
  • Enable the usage of apply, call, and bind in Javascript

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.