JavaScript Basics Collection _json (ix)

Source: Internet
Author: User

This series primarily records JavaScript, where beginners are more likely to be mistaken.

(1) Object-oriented programming

All JavaScript data can be viewed as objects, is it not that we are already using object-oriented programming? Of course not.

JavaScript does not classify and instance the concept, but uses the prototype (prototype) to implement object-oriented programming.

Prototypes mean that when we want to create xiaoming this specific student, we don't have a Student type available. So what? There happens to be a ready-made object:

  var robot = {      name: ‘Robot‘,      height: 1.6,      run: function () {    console.log(this.name + ‘ is running...‘);    }  };

We see this robot object has a name, height, and will run, a bit like xiaoming, simply according to it to "create" Xiao Ming won!

So we renamed it Student , and then we created xiaoming :

  var Student = {      name: ‘Robot‘,      height: 1.2,      run: function () {    console.log(this.name + ‘ is running...‘);    }  };  var xiaoming = {    name: ‘小明‘  };  xiaoming.__proto__ = Student;

Note that the last line xiaoming of code points to the object Student and looks xiaoming as if it inherits from it Student :

// ‘小明‘  xiaoming.run(); // 小明 is running...

  xiaomingHas its own name properties, but does not define the run() method. However, because Xiaoming is Student inherited from, as long as Student there are run() methods, xiaoming You can also call:

JavaScript's prototype chain and Java's class difference is that it does not have the concept of "class", all objects are instances, so-called inheritance is simply the prototype of one object point to another object.

If you xiaoming point the prototype to another object:

  var Bird = {      fly: function () {            console.log(this.name + ‘ is flying...‘);    }  };  xiaoming.__proto__ = Bird;

Now it xiaoming is impossible run() , he has become a bird:

// 小明 is flying...

When the Javascrip code is running, you can xiaoming turn Student Bird it into, or become, any object.

Please note that the above code is for illustrative purposes only. When writing JavaScript code, do not directly use obj.__proto__ to change the prototype of an object, and the lower version of IE is not available __proto__ . The Object.create() method can pass in a prototype object and create a new object based on that prototype, but the new object has no properties, so we can write a function to create xiaoming :

Prototype objects:var Student = {name:  ' Robot ', Height: 1.2, Run: function  () {Console.log (this.name + function createstudent (    Name) {//creates a new object based on Student prototype: var s = object.create (Student);    //initializes the new object: S.name = name;  return s;  } var xiaoming = createstudent (//Xiao Ming is running ... xiaoming.__proto__ = = Student; //true              

This is a way to create a prototype inheritance, and JavaScript has other ways to create objects.

(2) Create an object

  

JavaScript sets a prototype for each object that is created, pointing to its prototype object.

When we obj.xxx access the properties of an object, the JavaScript engine looks for the property on the current object, and if it is not found, it is found on its prototype object, and if it is not found, it is traced back to the Object.prototype object, and finally, if it is not found, it can only be returned undefined .

For example, create an Array object:

var arr = [1, 2, 3];

Its prototype chain is:

Array.prototype ----> Object.prototype ----> null

Array.prototypeDefines, and so on, indexOf() shift() so you can Array call these methods directly on all objects.

When we create a function:

function foo() {    return 0;}

The function is also an object, and its prototype chain is:

null

Because Function.prototype apply() such methods are defined, all functions can invoke apply() methods.

It is easy to think that if the prototype chain is long, then accessing an object's properties will become slower because it takes more time to find it, so be careful not to make the prototype chain too long.

constructor function

In addition to { ... } creating an object directly, JavaScript can also create objects using a constructor method. The use of it is to define a constructor first:

function Student(name) {    this.name = name; this.hello = function () { alert(‘Hello, ‘ + this.name + ‘!‘); }}

You would ask, eh, is this not a normal function?

This is really a normal function, but in JavaScript, you can new call this function with a keyword and return an object:

var xiaoming = new Student(‘小明‘);xiaoming.name; // ‘小明‘xiaoming.hello(); // Hello, 小明!

Note that if you do not write new , this is a normal function that returns undefined . However, if new it is written, it becomes a constructor that binds to the this newly created object and returns it by default this , that is, it does not need to be written at the last point return this; .

The newly created xiaoming prototype chain is:

null

In other words, xiaoming the prototype points to Student the prototype of the function. If you create again, xiaohong the xiaojun prototypes of these objects xiaoming are the same:

nullxiaojun  

new Student()the created object also obtains a property from the prototype constructor , which points to the function Student itself:

Student.prototype.constructor; // trueStudent.prototype.constructor === Student; // trueObject.getPrototypeOf(xiaoming) === Student.prototype; // truexiaoming instanceof Student; // true

You look dizzy, don't you? Using a graph to show that these messy relationships are:

The red Arrow is the prototype chain. Notice that the Student.prototype object that is pointing to is the xiaoming xiaohong prototype object, and the prototype object itself has a property constructor that points to the Student function itself.

In addition, the function Student has exactly prototype a xiaoming prototype object pointing to the property, xiaohong but xiaoming xiaohong these objects may not have prototype this property, but can be __proto__ viewed in this non-standard usage.

Now we think that xiaoming xiaohong these objects are "inherited" from Student .

However, there is a small problem, pay attention to observation:

// ‘小明‘xiaohong.name; // ‘小红‘xiaoming.hello; // function: Student.hello()xiaohong.hello; // function: Student.hello()xiaoming.hello === xiaohong.hello; // false

xiaomingIt's right to be xiaohong different from each name other, otherwise we can't tell who is who.

xiaomingand xiaohong each hello is a function, but they are two different functions, although the function name and code are the same!

If we new Student() create a lot of objects, the functions of these objects hello actually only need to share the same function, which can save a lot of memory.

To let the created object share a hello function, according to the object's property lookup principle, we just hello move the function to the xiaoming xiaohong Common prototype of these objects, that is Student.prototype :

Modify the code as follows:

function Student(name) {    this.name = name;}Student.prototype.hello = function () { alert(‘Hello, ‘ + this.name + ‘!‘);};

It's new so easy to create a prototype-based JavaScript Object!

Forget to write new what to do

What if a function is defined as the constructor used to create the object, but when the call forgets to write new ?

In strict mode, this.name = name will be error, because the this binding is undefined , in the non-strict mode, this.name = name no error, because the this binding is window , then inadvertently created a global variable name , and return undefined , this result is worse.

So, call the constructor and never forget to write new . In order to distinguish between ordinary functions and constructors, by convention, the initial letter of the constructor should be capitalized, and the first letter of the ordinary function should be lowercase, so that some grammar checking tools such as JSLint will be able to help you detect the missing write new .

Finally, we can also write a createStudent() function that encapsulates all the operations internally new . A common programming pattern is like this:

 function student  (props) {this.name = props.name | |  ' anonymous '; //default value is ' anonymous ' this.grade = Props.grade | | 1; //default value is 1} Student.prototype.hello = function  () {alert ( Span class= "string" > ' Hello, ' + this.name +  '! ');}; function createstudent ( Props) {return new Student (Props | | {})}< /span>       

This createStudent() function has several great advantages: one is not required new to call, the other is very flexible parameters, can not pass, can also be transmitted:

var xiaoming = createStudent({    name: ‘小明‘});xiaoming.grade; // 1

If you create an object that has many properties, we only need to pass some of the required properties, and the rest of the properties can be used as default values. Since the parameter is an object, we do not need to memorize the order of the parameters. If you happen JSON to get an object from it, you can create it directly xiaoming .

JavaScript Basics Collection _json (ix)

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.