Object-oriented Programming ideas (prequel)-JavaScript you must know

Source: Internet
Author: User

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.

-Reprint

Object-oriented Programming ideas (prequel)-JavaScript you must know

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.