Object-oriented Programming Ideas (prequel)-javascript you must know (reproduced)

Source: Internet
Author: User

Original Address: http://www.cnblogs.com/zhaopei/p/6623460.html
Read Catalogue
    • What is duck type
    • object-oriented JavaScript
    • Packaging
    • Inherited
    • Polymorphic
    • Prototype
    • This point
    • Pager
    • Apply
    • Band
    • The closure in JS
    • What is a higher order function

It is difficult to really understand and read JS object-oriented code when I write the object-oriented programming Idea-the JS part of the design pattern and find a lot of basic knowledge without understanding. To do this, first make a quick fill here. Then proceed with our object-oriented programming idea-design Pattern.

What is duck type

JavaScript is a typical dynamic type language, as well as a weakly typed language.
What is a duck type: "if it walks like a duck, it's a duck, then it's a duck."

var 鸭子 = {    走路: function () { },    咕咕咕: function () { }}var 鹦鹉 = { 走路: function () { }, 咕咕咕: function () { }}

The parrot also has a "walk" and "goo" method, that in the JS world can be used as a duck.
This can be called:

var 鸭子们 = [];鸭子们.push(鸭子);鸭子们.push(鹦鹉);for (var i = 0; i < 鸭子们.length; i++) { 鸭子们[i].走路();}

So JS of the world without abstraction and interface, but can be agreed that "we are all ducks."

object-oriented JavaScript

JavaScript is not only a literal scripting language, a dynamic type, a weakly typed language, a class-one Citizen's language, but also a prototype-based object-oriented language. Object-oriented three major features: encapsulation, inheritance, polymorphism, The following we use JS to achieve the Respective.

Packaging
var Person = (function () {     var sex = "纯爷们"; return { name: "农码一生", getInfo: function () { console.log("name:" + this.name + ",sex:" + sex); } };})();


Although the old JS syntax does not provide the private keyword, but we can use closures to implement private fields, to achieve the purpose of Encapsulation.

Inherited
    • Literal representation:

       var person = {name:  "farming code life", getName: function ( console.log (this.name);}; var obj = person;obj.getname ();          

    • Function constructor:

var Person = function () {    this.name = "农码一生"; }Person.prototype.getName = function () { console.log(this.name);}var obj = function () { };obj.prototype = new Person();//obj继承于Personvar o = new obj();o.getName();//直接调用原型中的getName(类似于C#中的调用父类方法)

Polymorphic

For polymorphism, the duck type above has been shown to be very clear.

var 鸭子们 = [];鸭子们.push(鸭子);鸭子们.push(鹦鹉);for (var i = 0; i < 鸭子们.length; i++) { 鸭子们[i].走路();//对于鹦鹉来说,它可能是跳着走。对于鸭子来说,它可能左右摇摆着走。这就是多态的表现。}

For parrots, it may be jumping away. For a duck, it may swing around. This is the manifestation of Polymorphism.

Prototype

What is a prototype? There is no class in js, then how does it create the Object. In C # We can instantiate an object by using the new keyword, and in JS we construct a prototype object with the new Keyword. The prototype of all objects in C # that inherits from Object,js is Object.

var Person = function () {    this.name = "农码一生"; this.sex = "纯爷们";};console.log(Person.prototype);


We often add a method to an object when it is written on the prototype, which is why? Is it a problem to write directly to the object? Let's try This:

var Person = function () {    this.name = "农码一生"; this.sex = "纯爷们"; this.getInfo = function () { console.log("name:" + this.name + ",sex:" + this.sex); }};


I don't think I can see any problems. Not actually ...

We find that the methods in each constructed object will open up a space. But the method of the object is the same, it is not necessary at All. We can put the method into the Prototype.

This way, however, we construct how many objects are common (singleton).
But why is that?
First of all, think of the word prototype, very image, the original model. Let's look at an example of inheritance:

var person =function () {THIS.name ="farming Code life";This.sex = "pure man"; this.getinfo = function (console.log ( "name:" + this.name + ", sex: "+ this.sex";}}; var Student = function (new person (); var s1 = new Student ();  var s2 = new Student ();  Console.log (s1.getinfo = = = s2.getinfo);            


Although GetInfo is directly implemented in person, the student prototype (prototype) is a singleton of the person Object. This means that no matter how many student objects are constructed, the GetInfo methods are the Same.
however, There are multiple getinfo methods for constructing multiple Person. therefore, we should put the GetInfo method into the Person's prototype.

var Person = function () {    this.name = "农码一生"; this.sex = "纯爷们"; };Person.prototype.getInfo = function () { console.log("name:" + this.name + ",sex:" + this.sex);};

We carefully scrutinize this sentence "put the GetInfo method into the Person's prototype", the Person's prototype is an object, that is to say the GetInfo method put into the object?
yes, No Letter please see:

What if prototypes and prototypes both implement the same approach? Let's guess which version will be printed BELOW.

var person =function () {THIS.name = "farming code life";}; var Student = function (new person (); var stu = new Student (); Student.prototype.getName = function ( console.log ( "my name:" + this.name);} Person.prototype.getName = function ( console.log ( "My name is:" + Span class= "hljs-keyword" >this.name);} Stu.getname ();                

What if I comment out the Chinese version?

There is no special magic, specific reasons we use the graph to Answer:

From another point of view, if an object implements a method that is already in the prototype, it is equivalent to a virtual method rewrite in C #.

This point
var name = "张三";var obj = {    name:"李四",    getName: function(){ console.log(this.name); }}obj.getName();


We should have no doubt about this Result.
Then look at the Following:

window.name = "张三";var obj = {    name:"李四",    getName: function(){ console.log(this.name); }} //obj.getName();window.func = obj.getName;window.func();


Is it dizzy? It doesn't matter, tell us a simple and practical way: the method is who "." out, this is pointing to Who.

Pager

"the Way is by whom." out, This is pointing to who ", this formula does not necessarily apply to all METHODS. Why do you say that? Please see Below:

window.name = "张三";var obj = {    name: "李四",    getName: function () { console.log(this.name); }}//obj.getName();window.func = obj.getName;window.func.call(obj);


Although it is still a window point, this already points to obj.
Because call can change this Execution.
This feature is very useful. For example, we want to write a drop-down check Event.

function func() {    console.log("我点击了" + $(this).find("option:selected").text());}$("#element1").change(function () { func.call(this);});$("#element2").change(function () { func.call(this);});

Do not consider the Drop-down box element when writing the Func method.

Apply

There is little difference between apply and Call.

func(age, sex) {    console.log("name:" + this.name + ",age:" + age + ",sex:" + sex);}var obj = { name: "晓梅"}func.call(obj, "18", "妹子");func.apply(obj,["18","小美女"]);


Call and apply the first parameter is the object to which this is Directed. Call second and later parameters correspond to the parameters of the method func. The second argument to apply is the array, which contains all the parameters of the Method.

Band
func(age, sex) {    console.log("name:" + this.name + ",age:" + age + ",sex:" + sex);}var obj = { name: "晓梅"}var func1 = func.bind(obj, "18", "妹子");func1();

The difference between apply and call is that just changing this point is not performed. And the parameters are passed in the same way as Call.

The closure in JS

What is a closure package? My understanding is that the existence of a variable that cannot be recycled is a closure.
The most common and largest closure is the global variable, which is defined and will not be destroyed unless it is automatically set to Null.
The closures we say and use are not so, but they also produce variables that will not be destroyed. Examples of private variables We've said Before:

var Person = (function () {     var sex = "纯爷们"; return { name: "农码一生", getInfo: function () { console.log("name:" + this.name + ",sex:" + sex); } };})();

The reason that it is a closure is because the sex field is never Destroyed. You think, if it was destroyed, we would not find the sex field when we called Getinfo. So it is not destroyed, but not destroyed.
The role of closures is not just Privatization. Let's take one more example:

for (var i = 0; i < 10; i++) {    var t = setTimeout(function () { console.log(i); }, 100);}


It's not as we thought. print 0 to 9.
Because the timer has not started the loop, it's Done. At this point the variable i is already 10.
We can save a closure variable for Each loop by a closure.

for (var i = 0; i < 10; i++) {    (function (i) { var t = setTimeout(function () { console.log(i); }, 100); })(i);}

What is a higher order function

"higher Order function" is a very cool name. In fact, we often use in js.
Or an example of a private variable:

var Person = (function () {     var sex = "纯爷们"; return { name: "农码一生", getInfo: function () { console.log("name:" + this.name + ",sex:" + sex); } };})();
    • When a function is return, it is the higher order Function.
var getInfo = function (callback) {    $.ajax(‘url‘, function (data) { if (typeof callback === ‘function‘) { callback(data); } });}getInfo(function (data) { alert(data.userName);});

When GetInfo is executing, the parameter passed in is a Function.

    • This is also a higher-order function when the function is passed as a parameter.

This article has been synchronized to the index directory: "design pattern learning"
"demo": Https://github.com/zhaopeiym/BlogDemoCode
"recommended": in-depth understanding of JavaScript prototypes and closures series

Object-oriented Programming Ideas (prequel)-javascript You must know (reprint)

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.