In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "what are the characteristics of JavaScript object-oriented thinking", so the editor summarizes the following contents, detailed contents, clear steps, and certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the characteristics of JavaScript object-oriented thinking" article.
1. Object oriented
Object-oriented is closer to our real life, and we can use object-oriented to describe things in the real world. But things are divided into concrete things and abstract things.
Characteristics of object-oriented thinking:
Extract (abstract) attributes and behaviors shared by objects and organize (encapsulate) into one class (template)
Instantiate the class to get the object of the class
1.1. Object
In JavaScript, an object is an unordered collection of related properties and methods, and all things are objects, such as strings, numeric values, arrays, functions, and so on.
Objects are made up of properties and methods
Attribute: the characteristic of a thing, represented by attributes in an object.
Method: the behavior of things, represented by methods in objects
1.2, CLA
The concept of a class has been added to ES6, and you can declare a class using the class keyword, and then instantiate an object with this class.
Class abstracts the public part of an object, which generally refers to a large class (class)
An object refers to a specific object and instantiates a concrete object through a class.
1.2.1. Create class class name {/ / class body}
Create an instance
Var XX = new name ()
Note: classes must instantiate objects using new
1.2.2, constructor
The constructor () method is the constructor of the class (the default method), which is used to pass parameters, return the instance object, and is automatically called when the object instance is generated through the new command. If the definition is not displayed, a constructor () is automatically created for us inside the class.
/ / 1. Create class class create a star class class Star {/ / constructor constructor or constructor constructor (uname, age) {this.uname = uname; this.age = age;}} / / 2. Use classes to create objects new var ldh = new Star ('Andy Lau', 18); var zxy = new Star ('Jacky Cheung', 20); console.log (ldh); console.log (zxy)
Using the class keyword to create a class, we still habitually define the initial capitalization of the class name.
There is a constructor function in the class that accepts the passed parameters and returns the instance object.
The constructor function will automatically call this function whenever new generates an instance. If we do not write this function, the class will automatically generate this function.
Finally, pay attention to grammar norms.
Do not add parentheses after creating a class ➡ class name
Generate instance ➡ class name followed by parentheses
Constructor does not need to add the function keyword
1.2.3. Add methods to the class
Syntax:
Class Person {constructor (name,age) {/ / constructor is called a constructor or constructor this.name = name; this.age = age;} say () {console.log (this.name + 'Hello');}} var ldh = new Person ('Andy Lau', 18); ldh.say ()
Note: methods cannot be separated by commas, and methods do not need to add the function keyword.
/ / 1. Create a class class create a star class class Star {/ / common attributes of the class into constructor constructor (uname, age) {this.uname = uname; this.age = age;} sing (song) {console.log (this.uname + song);}} / / 2. Use classes to create objects new var ldh = new Star ('Liu Dehua', 18); var zxy = new Star ('Jacky Cheung', 20); console.log (ldh); console.log (zxy); / / (1) all functions in our class do not need to write function / / (2) there is no need to add commas to separate ldh.sing ('ice rain') between multiple function methods Zxy.sing ('Li Xianglan')
The common properties of the class are put in the constructor
None of the functions in the class need to write the function keyword
1.3. Inheritance of classes
Inheritance in reality: a son inherits his father's work, for example, we all inherit his father's surname.
Inheritance in a program: subclasses can inherit some of the properties and methods of the parent class.
Syntax:
/ / parent class class Father {} / subclass inherits parent class class Son extends Father {}
Look at an example:
/ / the parent class has the addition method class Father {constructor (x, y) {this.x = x; this.y = y;} sum () {console.log (this.x + this.y) }} / / the subclass inherits the parent addition method while extending the subtraction method class Son extends Father {constructor (x, y) {/ / calling the constructor of the parent class using super / / super must call super (x, y) before the subclass this; this.x = x; this.y = y } subtract () {console.log (this.x-this.y);}} var son = new Son (5,3); son.subtract (); son.sum (); 1.4.The super keyword
The super keyword is used to access and call functions on the parent class of an object. You can call either the constructor of the parent class or the normal function of the parent class
1.4.1. Call the constructor of the parent class
Syntax:
/ / parent class class Person {constructor (surname) {this.surname = surname;}} / subclass inherits parent class class Student entends Person {constructor (surname,firstname) {super (surname); / / calls constructor (surname) this.firstname of the parent class = firstname; / / defines attributes unique to the subclass}}
Note: the subclass that uses super in the constructor must be placed before the this (the constructor of the parent class must be called first, and the constructor of the subclass must be used)
Case study:
/ / parent class class Father {constructor (surname) {this.surname = surname;} saySurname () {console.log ('my last name is'+ this.surname);}} / / subclass inherits parent class class Son entends Father {constructor (surname,firstname) {super (surname); / / calls constructor (surname) this.firstname = firstname of the parent class / / define properties unique to the subclass} sayFirstname () {console.log ('my name is:'+ this.firstname);}} var damao = new Son ('Liu', 'Dehua'); damao.saySurname (); damao.sayFirstname (); 1.4.2. Call the normal function of the parent class
Syntax:
Class Father {say () {return'I am the father';}} class Son extends Father {say () {/ / super.say () super calls the parent method return super.say () + 'son';}} var damao = new Son (); console.log (damao.say ())
There is no need to add comma separation between multiple methods
The principle of finding properties and methods in inheritance: the nearest principle, first look at the subclass, then look at the parent class
1.4. Three points for attention
Classes have no variable promotion in ES6, so classes must be defined before objects can be instantiated through classes.
The common properties and methods in the class must be used by this.
The this in the class points to:
The this in constructor points to the instance object
The this in the method points to the caller of the method
Click this in var that; var _ that; class Star {constructor (uname, age) {/ / constructor to point to the created instance object that = this; this.uname = uname; this.age = age; / / this.sing () This.btn = document.querySelector ('button'); this.btn.onclick = this.sing;} sing () {/ / the this in this sing method points to the button btn, because this button calls the function console.log (that.uname) / / what is stored in that is this} dance () {/ / the this in this dance points to the instance object ldh because ldh calls the function _ that = this; console.log (this). }} var ldh = new Star ('Andy Lau'); console.log (that = ldh); ldh.dance (); console.log (_ that = ldh); / / 1. The class has no variable promotion in ES6, so you must define the class before you can instantiate the object / / 2. The common properties and methods in the class must be used by this. 2. Constructors and prototypes 2.1, Overview
In a typical OOP language (such as Java), there is the concept of class, the class is the template of the object, and the object is the instance of the class, but before ES6, the concept of class was not introduced in JS.
ES6, full name ECMAScript 6.0, 2015.06 edition. However, at present, the JavaScript of the browser is the ES5 version, and most high-end browsers also support ES6, but only some of the features and functions of ES6 are implemented.
Before ES6, objects were not created based on classes, but were defined with a special function called a builder function and their characteristics.
There are three ways to create an object
Object literal quantity
New Object ()
Custom constructor
/ / 1. Use new Object () to create the object var obj1 = new Object (); / / 2. Use object literals to create object var obj2 = {}; / / 3. Use the constructor to create an object function Star (uname,age) {this.uname = uname; this.age = age; this.sing = function () {console.log ('I can sing');}} var ldh = new Star ('Andy Lau', 18)
Note:
Constructor is used to create a class of objects with uppercase initials
Constructors make sense only if they are used with new
2.2, constructor
Constructor is a special function that is mainly used to initialize objects (assign initial values to object member variables). It is always used with new
We can extract some common properties and methods from the object and encapsulate them into this function.
New does four things when it is executed
Create a new empty object in memory.
Let this point to this new object.
Execute the code in the constructor to add properties and methods to the new object.
Return this new object (so you don't need return in the constructor).
2.2.1, static members and instance members
Members can be added to the constructor of JavaScript, either on the constructor itself or on the this inside the constructor. Members that are added in these two ways are called static members and instance members, respectively.
Static members: members added to the constructor itself are static members and can only be accessed by the constructor itself
Instance members: object members created inside the constructor are called instance members and can only be accessed by instantiated objects
/ / the properties and methods in the constructor are called members. Members can add function Star (uname,age) {this.uname = uname; this.age = age; this.sing = function () {console.log ('I can sing');}} var ldh = new Star ('Andy Lau', 18) / / instance members are members added inside the constructor through this. Uname age sing is instance members / / instance members can only access ldh.sing () through instantiated objects; Star.uname / / undefined cannot access instance members through constructors / / static members are members added to the constructor itself sex is static members / / static members can only access Star.sex = 'male' through constructors; Star.sex;ldh.sex; / / undefined cannot access 2.2.2 through objects.
The constructor method works well, but there is a problem of wasting memory.
We want all objects to use the same function, which saves memory.
2.3.Constructor prototype prototype
The function assigned by the constructor through the prototype is shared by all objects, which solves the problem of memory waste.
JavaScript states that every constructor has a prototype property that points to another object. Note that this prototype is an object, and all the properties and methods of this object will be owned by the constructor.
We can define those immutable methods directly on the prototype object, so that all instances of the object can share these methods.
/ / 1. The problem of constructor. Function Star (uname, age) {/ / Common attribute is defined into the constructor this.uname = uname; this.age = age; / / this.sing = function () {/ / console.log ('I can sing') / / the public method we put on the prototype object Star.prototype.sing = function () {console.log ('I can sing');} var ldh = new Star ('Andy Lau', 18); var zxy = new Star ('Jacky Cheung', 19) Console.log (ldh.sing = zxy.sing); ldh.sing (); zxy.sing (); / / 2. In general, our public properties are defined in the constructor, and we put the public methods on the prototype object.
In general, our public properties are defined in the constructor, and we put the public methods on the prototype object.
Q: what is the prototype?
An object, also known as prototype, is a prototype object.
Question and answer: what is the function of the prototype?
Sharing method
2.4.Object prototype _ _ proto _ _
All objects have an attribute _ proto_ that points to the prototype prototype object of the constructor. The reason why our object can use the properties and methods of the constructor prototype prototype object is that the object has a _ proto_ prototype.
_ proto_ object prototype and prototype object prototype are equivalent
The meaning of the _ proto_ object prototype is to provide a direction, or a route, for the object lookup mechanism, but it is a non-standard attribute, so in actual development, this property cannot be used, it only points internally to the prototype object prototype.
Star.prototype and ldh._proto_ point to the same point.
Function Star (uname, age) {this.uname = uname; this.age = age;} Star.prototype.sing = function () {console.log ('I can sing');} var ldh = new Star ('Andy Lau', 18); var zxy = new Star ('Jacky Cheung', 19); ldh.sing () Console.log (ldh); / / the system itself adds a _ _ proto__ to the prototype object prototype console.log of our constructor (ldh.__proto__ = = Star.prototype) / / search rules for methods: first, check whether there is a sing method on the ldh object. If so, execute the sing / / if there is no sing method on this object, because of the existence of _ _ proto__, go to the constructor prototype object prototype to find the sing method 2.5, constructor constructor
Both the object prototype (_ _ proto _ _) and the constructor (prototype) prototype object have a property constructor property, which we call the constructor because it refers to the constructor itself.
Constructor is mainly used to record which constructor the object is referenced to. It allows the prototype object to repoint to the original constructor.
In general, the methods of the object are set in the prototype object of the prototype
If there are multiple object methods, we can assign the prototype object prototype as an object, but this will overwrite the original content of the constructor prototype object, so that the modified prototype object constructor no longer points to the current constructor. At this point, we can add a constructor to the modified prototype object to point to the original constructor
For details, please refer to the examples for cooperation and understanding.
Function Star (uname, age) {this.uname = uname; this.age = age;} / / in many cases, we need to manually use the attribute constructor to refer back to the original constructor / / Star.prototype.sing = function () {/ / console.log ('I can sing'); / /} / / Star.prototype.movie = function () {/ / console.log ('I can do a movie') / /} Star.prototype = {/ / if we modify the original prototype object and assign a value to the prototype object, we must manually use constructor to refer back to the original constructor constructor: Star, sing: function () {console.log ('I can sing') }, movie: function () {console.log ('I can make a movie');}} var ldh = new Star ('Andy Lau', 18); var zxy = new Star ('Jacky Cheung', 19); 2.6.The relationship among constructor, instance and prototype object
2.7. Prototype chain lookup rules
When accessing the properties of an object (including methods), first find out whether the object itself has the property
If not, find its prototype (that is, the prototype prototype object pointed to by _ proto_)
If not, find the prototype of the prototype object (the prototype object of Object)
And so on until Object is found (null)
The meaning of the _ _ proto _ _ object prototype is to provide a direction, or a route, for the object member lookup mechanism.
Function Star (uname, age) {this.uname = uname; this.age = age;} Star.prototype.sing = function () {console.log ('I can sing');} var ldh = new Star ('Andy Lau', 18); / / 1. As long as it is an object, there is a _ _ proto__ prototype, pointing to the prototype object console.log (Star.prototype); console.log (Star.prototype.__proto__ = Object.prototype); / / 2. The _ _ proto__ prototype in our Star prototype object points to Object.prototype console.log (Object.prototype.__proto__); / / 3. The _ _ proto__ prototype in our Object.prototype prototype object points to null 2.8and the prototype object this points to
The this in the constructor points to our instance object
The method is in the prototype object, and the this in this method points to the caller of the method, that is, the instance object.
Function Star (uname, age) {this.uname = uname; this.age = age;} var that; Star.prototype.sing = function () {console.log ('I can sing'); that = this;} var ldh = new Star ('Andy Lau', 18); / / 1. In the constructor, this points to the object instance ldh ldh.sing (); console.log (that = ldh); / / 2. The this in the prototype object function points to the instance object ldh 2.9.Extensible built-in object
You can extend and customize the original built-in object through the prototype object.
For example, the function of adding a custom courtship sum to an array
/ / the application of the prototype object extends the built-in object method Array.prototype.sum = function () {var sum = 0; for (var I = 0; I
< this.length; i++) { sum += this[i]; } return sum; }; // Array.prototype = { // sum: function() { // var sum = 0; // for (var i = 0; i < this.length; i++) { // sum += this[i]; // } // return sum; // } // } var arr = [1, 2, 3]; console.log(arr.sum()); console.log(Array.prototype); var arr1 = new Array(11, 22, 33); console.log(arr1.sum()); 注意: 数组和字符串内置对象不能给原型对象覆盖操作Array.prototype = {},只能是Array.prototype.xxx = function(){}的方式 3、继承 ES6 之前并没有给我们提供extends继承 我们可以通过构造函数+原型对象模拟实现继承,被称为组合继承 3.1、call() 调用这个函数,并且修改函数运行时的 this 指向 fun.call(thisArg,arg1,arg2,......) thisArg:当前调用函数 this 的指向对象 arg1,arg2: 传递的其他参数 示例 // call 方法 function fn(x, y) { console.log('我希望我的希望有希望'); console.log(this); // Object{...} console.log(x + y); // 3 } var o = { name: 'andy' }; // fn(); // 1. call() 可以调用函数 // fn.call(); // 2. call() 可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象 fn.call(o, 1, 2); 3.2、借用构造函数继承父类型属性 核心原理: 通过 call() 把父类型的 this 指向子类型的 this,这样就可以实现子类型继承父类型的属性 // 借用父构造函数继承属性 // 1. 父构造函数 function Father(uname, age) { // this 指向父构造函数的对象实例 this.uname = uname; this.age = age; } // 2 .子构造函数 function Son(uname, age, score) { // this 指向子构造函数的对象实例 Father.call(this, uname, age); this.score = score; } var son = new Son('刘德华', 18, 100); console.log(son); 3.3、借用原型对象继承父类型方法 一般情况下,对象的方法都在构造函数的原型对象中设置,通过构造函数无法继承父类方法 核心原理: 将子类所共享的方法提取出来,让子类的 prototype 原型对象 = new 父类() 本质: 子类原型对象等于是实例化父类,因为父类实例化之后另外开辟空间,就不会影响原来父类原型对象 将子类的constructor重新指向子类的构造函数 // 借用父构造函数继承属性 // 1. 父构造函数 function Father(uname, age) { // this 指向父构造函数的对象实例 this.uname = uname; this.age = age; } Father.prototype.money = function() { console.log(100000); }; // 2 .子构造函数 function Son(uname, age, score) { // this 指向子构造函数的对象实例 Father.call(this, uname, age); this.score = score; } // Son.prototype = Father.prototype; 这样直接赋值会有问题,如果修改了子原型对象,父原型对象也会跟着一起变化 Son.prototype = new Father(); // 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数 Son.prototype.constructor = Son; // 这个是子构造函数专门的方法 Son.prototype.exam = function() { console.log('孩子要考试'); } var son = new Son('刘德华', 18, 100); console.log(son); console.log(Father.prototype); console.log(Son.prototype.constructor); 3.3 类的本质 class 本质还是 function 类的所有方法都定义在类的 prototype属性上 类创建的实例,里面也有_proto_指向类的prototype原型对象 所以 ES6 的类它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。 所以 ES6 的类其实就是语法糖 语法糖:语法糖就是一种便捷写法,简单理解 4、ES5新增方法 ES5 给我们新增了一些方法,可以很方便的操作数组或者字符串 数组方法 字符串方法 对象方法 4.1、数组方法 迭代(遍历)方法:foreach() ,map(),filter(),some() ,every() ; 4.1.1、forEach()array.forEach(function(currentValue,index,arr)) currentValue: 数组当前项的值 index: 数组当前项的索引 arr: 数组对象本身 // forEach 迭代(遍历) 数组 var arr = [1, 2, 3]; var sum = 0; arr.forEach(function(value, index, array) { console.log('每个数组元素' + value); console.log('每个数组元素的索引号' + index); console.log('数组本身' + array); sum += value; }) console.log(sum); 4.1.2、filter()筛选数组array.filter(function(currentValue,index,arr)) filter()方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素,主要用于筛选数组 注意它直接返回一个新数组 // filter 筛选数组 var arr = [12, 66, 4, 88, 3, 7]; var newArr = arr.filter(function(value, index) { // return value >= 20; return value% 2 = 0;}); console.log (newArr); 4.1.3, some ()
The some () method is used to detect whether the elements in the array meet the specified conditions (to find out if there are any elements in the array that meet the conditions).
Note that it returns a Boolean value. If this element is found, true is returned, and false is returned if it is not found.
If the first element that meets the criteria is found, the loop is terminated and the search is stopped.
/ / some finds whether there are elements in the array that meet the criteria: var arr1 = ['red',' pink', 'blue']; var flag1 = arr1.some (function (value) {return value = =' pink';}); console.log (flag1) / / 1. Filter also looks for elements that meet the criteria, returns an array and returns all elements that meet the conditions / / 2. Some also looks for the existence of elements that meet the criteria and returns a Boolean value that terminates the loop 4.2, string method if the first element that meets the condition is found.
The trim () method removes white space characters from both ends of a string
The trim () method does not affect the original string itself, it returns a new string
Click
/ / the trim method removes the spaces on both sides of the string var str ='an dy'; console.log (str); var str1 = str.trim (); console.log (str1); var input = document.querySelector ('input'); var btn = document.querySelector (' button'); var p = document.querySelector ('p') Btn.onclick = function () {var str = input.value.trim (); if (str =') {alert ('Please enter content');} else {console.log (str); console.log (str.length); p [XSS _ clean] = str }} 4.3, object method 4.3.1, Object.keys ()
Object.keys () is used to get all the properties of the object itself.
The effect is similar to for...in.
Returns an array of attribute names
/ / used to get all the attributes of the object var obj = {id: 1, pname: 'Xiaomi', price: 1999, num: 2000}; var arr = Object.keys (obj); console.log (arr); arr.forEach (function (value) {console.log (value)) / / id / / pname / / price / / num}) 4.3.2, Object.defineProperty ()
Object.defineProperty () defines a new property in an object or modifies an existing property (understand)
Object.defineProperty (obj,prop,descriptor)
Obj: target object
Prop: the name of the attribute to be defined or modified
Descriptor: properties owned by the target attribute
/ / Object.defineProperty () define a new attribute or modify the original attribute var obj = {id: 1, pname: 'millet', price: 1999}; / / 1. The way previous objects add and modify properties / / obj.num = 1000; / / obj.price = 99; / / console.log (obj); / 2. Object.defineProperty () defines a new property or modifies an existing property Object.defineProperty (obj, 'num', {value: 1000, enumerable: true}) Console.log (obj); Object.defineProperty (obj, 'price', {value: 9.9}); console.log (obj); Object.defineProperty (obj,' id', {/ / if the value is false, the default value of this attribute is also false writable: false,}); obj.id = 2 Console.log (obj) Object.defineProperty (obj, 'address', {value:' xx Unit of Shandong Lanxiang Technical School, China', / / if it is only false, the default value of this attribute is also false writable: false, / / enumerable is false, traversal is not allowed, and the default value is false enumerable: false / / configurable this property is not allowed to be deleted if it is false. The property in the third parameter modified is false configurable: false} by default.) Console.log (obj); console.log (Object.keys (obj)); delete obj.address; console.log (obj); delete obj.pname; console.log (obj) Object.defineProperty (obj, 'address', {value:' xx Unit of Shandong Lanxiang Technical School, China', / / if the value is false, the default value of this attribute is also false writable: true, / / enumerable is not allowed to traverse if the value is false, and the default value is false enumerable: true / / configurable is not allowed to be deleted if it is false. Default is false configurable: true}) Console.log (obj.address)
The third parameter descriptor description: write in object form {}
Value: sets the value of the property. The default is undefined.
Writeable: whether the value can be overridden true | false defaults to false
Enumerable: whether the target attribute can be enumerated true | false defaults to false
| configurable: whether the target attribute can be deleted or whether the attribute true can be modified again | false defaults to false |
5. Function advance 5.1, the definition of function
Function declaration mode function keyword (named function)
Function expression (anonymous function)
New Function ()
Var fn = new Function ('parameter 1,' parameter 1', 'parameter 2',' body', 'function body')
All parameters in Function must be in string format.
The third method is inefficient and inconvenient to write, so it is rarely used.
All functions are instances (objects) of Function
Functions also belong to objects
/ / the definition of the function / / 1. Custom function (named function) function fn () {}; / / 2. Function expression (anonymous function) var fun = function () {}; / / 3. Using new Function ('parameter 1', 'function body'); / / Function, all the parameters must be in string format, so it is inefficient to write var f = new Function ('a', 'baked,' console.log (a + b)'); f (1, 2); / / 4. All functions are instances of Function (object) console.dir (f); / / 5. The function also belongs to the object console.log (f instanceof Object). 5.2. the way the function is called
Ordinary function
Method of object
Constructor function
Bind event function
Timer function
Execute the function immediately
/ / the method of calling the function / / 1. Ordinary function function fn () {console.log ('the pinnacle of life');} / / fn (); fn.call () / / 2. Object's method var o = {sayHi: function () {console.log ('the pinnacle of life');}} o.sayHi (); / / 3. Constructor function Star () {}; new Star (); / / 4. Bind event function / / btn.onclick = function () {}; / / you can call this function / / 5 at the click of a button. Timer function / / setInterval (function () {}, 1000); this function is called automatically by the timer once a second / / 6. Execute the function immediately (function () {console.log ('the pinnacle of life');}) (); / / execute the function automatically and point to this within the function
The this point is determined when we call the function, and the different way of calling determines the different direction of the this. Generally speaking, we point to our caller.
The calling mode this points to the ordinary function to call the window constructor to call the instance object, and the method in the prototype object also points to the instance object method to call the object to which the method belongs. The event binding method binds the event object timer function window immediately executes the function window clicks / / the function is called in different ways that determine the different points to this / / 1. The ordinary function this points to window function fn () {console.log ('this' + this of ordinary functions);} window.fn (); / / 2. The object method this points to the object o var o = {sayHi: function () {console.log ('this:' + this of the object method);}} o.sayHi (); / / 3. The constructor this points to the this in the ldh instance object prototype object, which also points to the ldh instance object function Star () {}; Star.prototype.sing = function () {} var ldh = new Star (); / / 4. The binding event function this points to the function's caller btn the button object var btn = document.querySelector ('button'); btn.onclick = function () {console.log (' this:' + this of the binding time function);}; / / 5. The timer function this also points to window window.setTimeout (function () {console.log ('timer this:' + this);}, 1000); / / 6. Whether to execute the function this immediately or to point to window (function () {console.log ('this' + this for immediate execution of the function);}) (); 5.4.change the this inside the function to point to
JavaScript specially provides us with some function methods to help us deal with the pointing problem of this inside the function. The commonly used methods are bind (), call () and apply ().
5.4.1, call () method
The call () method calls an object, which is simply understood as the way the function is called, but it can change the this direction of the function.
Fun.call (thisArg,arg1,arg2,.)
ThisArg: the this value specified when the fun function is running
Arg1,arg2: other parameters passed
The return value is the return value of the function, because it is the calling function.
So when we want to change the this direction and call this function, we can use call, such as inheritance
/ / changing the this in the function to js provides three methods: call () apply () bind () / / 1. Call () var o = {name: 'andy'} function fn (a, b) {console.log (this); console.log (a + b);}; fn.call (o, 1, 2) / / call the first can call the function and the second can change the main role of this pointing to / / call in the function to inherit function Father (uname, age, sex) {this.uname = uname; this.age = age; this.sex = sex } function Son (uname, age, sex) {Father.call (this, uname, age, sex);} var son = new Son ('Andy Lau', 18, 'male'); console.log (son); 5.4.2, apply () method
The apply () method calls a function, which is simply understood as the way the function is called, but it can change the this direction of the function.
Fun.apply (thisArg, [argsArray])
ThisArg: the this value specified when the fun function is running
ArgsArray: the value passed, which must be included in the array
The return value is the return value of the function, because it is the calling function.
So apply is mainly related to arrays, such as using Math.max () to find the maximum value of an array.
/ / changing the this to js in the function provides three methods: call () apply () bind () / / 2. The meaning of apply () application is var o = {name: 'andy'}; function fn (arr) {console.log (this); console.log (arr); / /' pink'} Fn.apply (o, ['pink']) / / 1. It is also the second one that can change the internal this of the function to / / 2. But its parameters must be array (pseudo array) / / 3. The main application of apply, for example, we can use apply to find the maximum value of the array / / Math.max () with the help of mathematical built-in objects; var arr = [1,66,3,99,4]; var arr1 = ['red',' pink']; / / var max = Math.max.apply (null, arr) Var max = Math.max.apply (Math, arr); var min = Math.min.apply (Math, arr); console.log (max, min); 5.4.3, bind () method
The bind () method does not call the function. But it can change the this point inside the function.
Fun.bind (thisArg,arg1,arg2,....)
Returns a copy of the original function modified by the specified this value and initialization parameters
So when we just want to change the this direction and don't want to call this function, we can use bind
Click click / / change the this in the function to point to js provides three methods: call () apply () bind () / / 3. Bind () the meaning of binding bundle var o = {name: 'andy'}; function fn (a, b) {console.log (this) Console.log (a + b);}; var f = fn.bind (o, 1,2); f (); / / 1. Will not call the original function can change the original function inside the this point to / / 2. What is returned is the new function / / 3 generated after the original function changes this. If there is a function we do not need to call immediately, but we want to change the this inside the function to point to bind / / 4 at this time. We have a button, and when we click it, disable it and turn on the button / / var btn1 = document.querySelector ('button') after 3 seconds; / / btn1.onclick = function () {/ / this.disabled = true; / / this this points to the button btn / var that = this / / setTimeout (function () {/ that.disabled = false; / / timer function this points to window / / this.disabled = false; / / at this time the this in the timer function points to btn / /} .bind (this), 3000) / / this this points to the object btn / /} var btns = document.querySelectorAll ('button'); for (var I = 0; I < btns.length; iTunes +) {btns.onclick = function () {this.disabled = true; setTimeout (function () {this.disabled = false) } .bind (this), 2000);} 5.4.4, summary
Call apply bind Summary:
Similarities:
Can change the this point inside the function.
The difference:
Call and apply call the function and change the this inside the function to point to
The parameters passed by call and apply are different. Call passes parameters, and apply must be in array form.
Bind will not call the function, so you can change the internal this of the function to point to
Main application scenarios
Call often does inheritance.
Apply is often related to arrays, such as realizing the maximum and minimum values of arrays with the help of mathematical alignment
Bind does not call functions, but also wants to change the this direction, such as changing the this point inside the timer.
The above is the content of this article on "what are the characteristics of JavaScript object-oriented thinking". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.