I. review
1.1 Review Context
Calling method of function |
context |
fun() |
window |
obj.fun() |
obj |
box.onclick = fun |
box |
setInterval(fun,1000) setTimeout(fun,1000) |
window |
array[8]() |
array |
new fun() |
Secretly Creating New Objects |
See who the final function caller is.
IIFE is also run directly as a function. IIFE's this is all window s objects.
The arguments of a function are class array objects, such as the argument [0](), whose context is the arguments object. Also know the difference between arguments.length and length of a function.
1.2 constructor
When a function is called with a new operator, it is called a constructor.
The constructor takes four steps:
Create a new empty object This is bound to this empty object Execution statement Return this object
All new objects have the same group of attributes, so the constructor can be regarded as a class, and the new objects are instances of this function.
When there is a return statement in the constructor, note that:
l. Ignore the return if it is a return primitive type value, or return the secret created object
l. If it is a return reference type value, it does not return the original object, but the reference type value.
Knowledge of prototype chains:
The prototype attribute of the constructor is the _proto_ attribute of the instance. For an object, _proto_ is called its own prototype object, which is its own prototype chain. This prototype chain has a lookup function. When obj.haha, there is no haha attribute on obj. At this time, it will find whether there is haha attribute on obj. proto and will continue to find whether there is haha attribute on obj. proto attribute...
II. Prototype Chain
Object.prototype is the end point of all object prototype chains
Every object has a prototype object (_proto_), which eventually points to Object.prototype, but Object.prototype is very special, and its _proto_ end point is null.
In JS, objects are objects, functions, arrays, regularities, etc. All reference type values are objects, and they all have _proto_ attributes.
Even xiaoming's _proto_ is an object, which also has _proto_.
var obj = {} console.log(obj.__proto__ === Object.prototype); //true
Object() is a built-in constructor, and all objects can be considered Object new
var obj = new Object(); obj.name = "Xiao Ming"; obj.age = 12; console.log(obj) console.log(obj.__proto__ === Object.prototype);
The _proto_ of the {} object points to Object.prototype, because it is all Object new.
function People(name,age){ this.name = name; this.age = age; } var xiaoming = new People("Xiao Ming",12); console.log(xiaoming.__proto__ === People.prototype); //true console.log(xiaoming.__proto__.__proto__ === Object.prototype); //true console.log(xiaoming.__proto__.__proto__.__proto__);; //null
To sum up, xiaoming's prototype People.prototype also has a prototype, xiaoming's complete family tree:
Object.prototype is the only object without _proto_. All other objects, functions, arrays, regularities, etc. have _proto.__
3. Built-in constructors
JS has many built-in constructors, which are also called wrapper classes of "base type values" and "reference type values".
3.1 Constructors that refer to type values
Constructors that reference type values: Object(), Function(), Array(), RegExp()
3.1.1 Object() function
Object() is a built-in constructor that can directly new it, return an empty object, and add attributes to the empty object:
var obj = new Object(); obj.name = "Xiao Ming"; obj.age = 12; console.log(obj) console.log(obj.__proto__ === Object.prototype);
Equivalent to:
var obj = { name:"Xiao Ming", age:12 }
3.1.2 Function() Function
All function literals are examples of it
function sum(a,b){ alert(a+b); } sum(3,5);
Equivalent to:
var sum = new Function("a","b","alert(a+b);alert('Finished!')"); sum(4,5)
In the new Function, list all the parameters first, and the last parameter is the function body. Note that the parameters are strings.
console.log(sum.__proto__ === Function.prototype)
Any function is an instance of a Function() constructor, and Object is also an instance of Function. Function itself is its own instance. Function itself new itself.
console.log(Object.__proto__ === Function.prototype); //true console.log(Function.__proto__ === Function.prototype); //true
The relationship between Function and Object:
console.log(Function.prototype.__proto__ === Object.prototype); console.log(Function.__proto__.__proto__ === Object.prototype); console.log(Function.__proto__.__proto__ === Object.__proto__.__proto__); console.log(Function.__proto__ === Object.__proto__);
3.1.3 Array() function
Array() is the built-in array constructor of the system. Any array is generated by Array() new.
var arr = new Array(); arr[0] = 100; arr[1] = 200; arr[2] = 300; console.log(arr);
Equivalent to:
var arr = [100,200,300];
Functions can fill in parameters to represent the length of an array, but the array is empty:
var arr = new Array(8);
The commonly used array methods are defined on Array.prototype.
var arr = [3,3,4,4]; console.log(arr.__proto__ === Array.prototype); //true console.log(arr.__proto__.__proto__ === Object.prototype); //true
3.1.4 RegExp() function
An instance of any regular expression RegExp() function.
var reg = /\d/g; //Equivalent to var reg = new RegExp("d","g");
console.log(reg.__proto__ === RegExp.prototype); //true console.log(reg.__proto__.__proto__ === Object.prototype); //true
3.2 Basic Type Value "Packaging Class"
[Number(),String(),Boolean()]
The constructor of a basic type value is called a "wrapper class". For the sake of completeness, the JS system has manually created these three packaging classes, which are of little use.
3.2.1 Number() function
Used to create digital objects:
var a = new Number(3); console.log(a) console.log(typeof a)
When you create a number with a built-in constructor, you get an object whose original value attribute is:
[[PrimitiveValue]]: 3 //This property cannot be enumerated.
It differs from literal quantities in creating numbers:
var a = new Number(3); var b = 3; console.log(a == b); //true console.log(a === b); //false
Objects created with Number() can participate in mathematical operations:
An instance of Number is an object, but once the parameter is calculated, the object becomes a normal Number type.
var a = new Number(3); a = a * 3 console.log(a) console.log(typeof a)
Number() can also be used to convert various values into arrays (which cannot be converted to NaN) without the need for a new call.
console.log(Number("12")); //12 console.log(Number("12 year")); //NaN console.log(Number("")); //0 console.log(Number(false)); //0 console.log(Number(true)); //1 console.log(Number({})); //NaN console.log(Number([])); //0 console.log(Number([1,2])); //NaN
Any implicit conversion that requires conversion to numbers is actually a call to the Number function.
3.2.2 String() function
var str = new String("I like you"); console.log(str)
String() can also be used to convert:
console.log(String(123)); //"123" console.log(String(true)); //"true" console.log(String([])); //"" console.log(String([1,2,3])); //"1,2,3" console.log(String(NaN)); //"NaN" console.log(String({})); //"[Object Object]"
3.2.3 Boolean() function
Whether the value is false or true, it can be verified by if, which is true.
var b = new Boolean(false); console.log(b) console.log(typeof b); if(b){ alert("Really?"); }
3.3 Relationships between built-in constructors
In just three sentences, memorize:
1. The'{}'object is generated by Object new. So its _proto_ points to Object.prototype. 2. Any function is an instance of Function new, so as long as it is a function (constructor is also a function), its _proto_ will point to Function.prototype. 3. Function is the mother of all constructors, and it is its own mother.
Xiao Ming is not from Object new, but from People new. Its _proto_ points to People.prototype.
console.log(Object.__proto__.__proto__ === Object.prototype); //true console.log(Function.__proto__.__proto__ === Object.prototype); //true console.log(Object.__proto__ === Function.prototype); //true console.log(Function.__proto__ === Function.prototype); //true console.log(Array.__proto__ === Function.prototype); //true console.log(RegExp.__proto__ === Function.prototype); //true console.log(Number.__proto__ === Function.prototype); //true console.log(String.__proto__ === Function.prototype); //true console.log(Boolean.__proto__ === Function.prototype); //true
4. Relevant methods, attributes, operators
4.1 hasOwnProperty() method
Returns a Boolean value (true/false) to detect an attribute, whether a method is on itself.
function People(name){ this.name = name; } People.prototype.sayHello = function(){ alert("Hello"); } var xiaoming = new People("Xiao Ming"); console.log(xiaoming.hasOwnProperty("name")); //true console.log(xiaoming.hasOwnProperty("sayHello")); //false console.log(xiaoming.hasOwnProperty("toString")); //false
4.2 in operator
Returning a Boolean value (true/false), the in operator checks whether an object has the ability to call an attribute or a method, regardless of whether the attribute or method is negative on itself or on the prototype.
Character string in object function People(name){ this.name = name; } People.prototype.sayHello = function(){ alert("Hello"); } var xiaoming = new People("Xiao Ming"); console.log("name" in xiaoming); //true console.log("sayHello" in xiaoming); //true console.log("toString" in xiaoming); //true
4.3 constructor attribute
Each function's prototype object has a constructor attribute that points to the constructor.
function People(name){ this.name = name; } var xiaoming = new People("Xiao Ming"); console.log(People.prototype) console.log(People.prototype.constructor === People); //true console.log(People.prototype.hasOwnProperty("constructor")); //true console.log(xiaoming.constructor === People); //true console.log(xiaoming.hasOwnProperty("constructor")); //false
4.4 instanceof operator
Returns a Boolean value to check whether an object is an instance of a function?
o instanceof F
If F.prototype is on the prototype chain of o, return true, otherwise return false.
function People(name){ this.name = name; } var xiaoming = new People("Xiao Ming"); function Dog(){ } console.log(xiaoming instanceof People); //true console.log(xiaoming instanceof Object); //true console.log(xiaoming instanceof Dog); //false
Topic:
console.log(Object instanceof Object); //true console.log(Function instanceof Function); //true console.log(Function instanceof Object); //true console.log(Number instanceof Function); //true console.log(Number instanceof Number); //false
We found that object.prototype is the end of all object prototype chains, so I dare say that any prototype X must be true.
x instanceof Object Function Of prototype Appearing in oneself__proto__Online, so yes true console.log(Function instanceof Function); //true
5. Exercise Questions
5.1 topic 1
function A(){} function B(){ return new A(); //Reference type value returned } A.prototype = B(); //Returns a A Example 1 B.prototype = new B();//Returns a A Example 2 var a = new A(); //Returns a A Examples given a var b = new B(); //Returns a A Examples given b console.log(a.__proto__ == b.__proto__); console.log(a instanceof A); //true console.log(a instanceof B); // false console.log(b instanceof A); //true console.log(b instanceof B); //false
5.2 topic 2
[].constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor.constructor === Function
Answer: true.
Six, inheritance
6.1 What Is Inheritance
In the field of computer, we pay attention to the relationship between two classes, that is, to see the relationship between attribute groups.
For example: human and dog attributes will inevitably intersect, but not completely overlap, at this time can be considered that there is no relationship between the two categories.
Look at the attributes of people and students:
Pupils must be human beings. They have all the attributes of human beings. They can do all the things that human beings can do.
But conversely, the attributes and abilities of pupils are not necessarily available.
We say:
"Student" has refined, refined and more specific "person". There are fewer examples of "students" than of "people". "Student" must be a person, but "person" is not necessarily a student.
Terminologically, we call it "extend ed" human beings. Human beings are called "superclass" and student classes are called "subclass".
Who do people inherit? Man inherits mammals, and mammals inherit creatures.
At this time, the computer primary and secondary school class inherits (extend s) human beings.
A inherits B, and at this point realize that: A has all the attributes and methods of B. The attribute group of A is larger than that of B. A enriches B, A makes B more specific and narrower.
6.2 JavaScript Implementation Inheritance
JavaScript implements two classes: the People class and the Student class, which require the attributes and methods of the People class, and the instances of the Student class also have the attributes and methods of the People class. Student can also enrich the attributes and methods of its own classes. It is very simple and requires only clever design of prototype chains.
//Human beings function People(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } People.prototype.sayHello = function(){ alert("Hello, I am." + this.name); } People.prototype.sing = function(){ alert("Dulamy is furious.~~~"); } // Student class function Student(name,age,sex,id,banji,socre){ People.apply(this, arguments) // this.name = name; // this.age = age; // this.sex = sex; this.id = id; this.banji = banji; this.socre = socre; } //The following statement implements inheritance Student.prototype = new People(); Student.prototype.study = function(){ alert(this.name + "I'm learning!"); } var xiaoming = new Student("Xiao Ming",12,"male",100001,"Class one in Junior Three", 100) xiaoming.study(); xiaoming.sayHello(); xiaoming.sing();
Note: The red statement must appear before Student.prototype.*** = function(){}.
John Resig, founder of jQuery, wrote a small package with more than 20 lines of code to solve the nausea of JS inheritance.
https://johnresig.com/blog/simple-javascript-inheritance/
After introducing the package, the package changes the way we create JS classes (like jQuery, changing the way we write JS)
//Human beings var People = Class.extend({ init : function(name,age,sex){ this.name = name; this.age = age; this.sex = sex; }, sayHello:function(){ alert("Hello, I am." + this.name); }, sing:function(){ alert("Dulamy is furious about Rashi~~~"); } }) //Student class var Student = People.extend({ init : function(name,age,sex,id,banji,socre){ this._super(name,age,sex); //Inheritance of the attributes of the parent class // this.name = name; // this.age = age; // this.sex = sex; this.id = id; this.banji = banji; this.socre = socre; }, study :function(){ alert(this.name + "I'm learning!"); } }) var xiaoming = new Student("Xiao Ming",12,"male",100001,"Class one in Junior Three", 100) console.log(xiaoming) xiaoming.study(); xiaoming.sing();
7. Upgrading to Object-Oriented
Object-oriented programming is a kind of thinking, two words can be summarized: autonomy (self-management), in-depth understanding, is encapsulation. Each individual object only needs to manage itself.
In the initial stage of object-oriented learning, when you encounter a large number of objects with the same structure, function, nature and everything, you immediately think of using object-oriented technology.
Now I want to give you a thinking formula, how to program in object-oriented time: Consider which classes are included in the initial program. In the early stage, our business only has one class, and in the later stage, there will be more than one class. What methods and attributes each class has is what functions they have. How each class communicates and interacts with each other? Design patterns such as mediator mode and publish-subscribe mode (observer mode) are needed at this time. How does this class perform unit testing? If we guarantee that our class is robust, every class is robust, and the whole program is robust. Our previous programming was called "process-oriented" and now "object-oriented" programming (OO)
7.1 Object-Oriented Traffic Light (Case)
Consider a problem, the page to produce an effect: 100 traffic lights, click on a traffic light, from the red light to the Yellow light, click again from the yellow light to the green light, click again on the green light to the red light.
There is a semaphore. After clicking the button, the semaphore changes 0, 1, 2, 0, 1, 2, 0, 1, 2... and then the background-position of the div changes. You need to write 100 semaphores, 100 boxes, 100 events.
What appears on the page is the traffic lights, and they have the same appearance, nature, function, so you can make the traffic lights design into a class.
What is the responsibility of each class: state variables and DOM elements.
There are two attributes in each JS object, one is the state attribute and the other is the DOM object.
Simply put, DOM objects are now an attribute of JS objects.
What attributes does this class have? DOM attributes Color attributes What methods? Initialization method init() changeToColor() Bound event method bindEvent()
Step 1: DOM structure and CSS style to ensure that a div element can see the light coming out.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Document</title> <style type="text/css"> *{ margin: 0; padding: 0;} div.honglvdeng{ position: relative; width: 140px; height: 328px; background: url(./images/honglvdeng.jpg); } </style> </head> <body> <div id="box"> <div class="honglvdeng"></div> </div> </body> </html>
//Step 2: Create a traffic light class //new Honglvdeng()When the constructor is executed, the statement in the constructor is executed //So create one in the constructor DOM Object, and then make it tree function Honglvdeng(){ //There are two attributes in each class: state variables, DOM this.dom = null; //State attribute this.state = 0; //Initialization method this.init(); //onclick this.bindEvent(); } //In order to make the program beautiful, neat, easy to change and pluggable, easy to maintain, we will DOM Both the upper tree statement and the upper tree statement are written in the initialization method Honglvdeng.prototype.init = function(){ //Establish DOM this.dom = document.createElement('div'); //to DOM Add class name this.dom.className = 'honglvdeng'; //Upper tree document.getElementById("box").appendChild(this.dom); } //Step 3: Adding event monitoring Honglvdeng.prototype.bindEvent = function(){ //backups this,Because it's in the event monitor. this Express dom Element itself var self = this; this.dom.onmouseenter = function(){ // Change the semaphore // self.state++; // if(self.state > 2) self.state = 0 //Judgment shorthand self.state = ++self.state % 3; self.dom.style.backgroundPositionX = -155 * self.state +'px'; } } //Step 4: Instantiate 100 traffic lights var count = 100; while(count--){ new Honglvdeng(); }