object
Using the knowledge you have learned, describe the person in your mind
Var mrDeng = {name: "mrDeng", age: 40, sex: "male", health: 100,// can change in console smoke: function () { console.log('I am smoking'); mrDeng.health --; }, drink : function () { console.log('I am drink'); mrDeng.health ++; }}Copy the code
Improve the first person: this
Var mrDeng = {name: "mrDeng", age: 40, sex: "male", health: 100,// function () { console.log('I am smoking'); this.health --; }, drink : function () { console.log('I am drink'); this.health ++; }}Copy the code
1. Add, delete, modify and search attributes
increase
drink:function(){
console.log('I am drinking');
this.health ++;
}
meDeng.wife = "xiaowang";
// console.log(mrDeng.wife = "xiaoliu");
// console.log(mrDeng);
Copy the code
change
console.log(mrDeng);
console.log(mrDeng.sex = "male");
console.log(mrDeng.sex);
Copy the code
Delete The delete + attribute
When a variable is not declared, an error is reported. If an object property is not declared, it will print undefined
var deng = { prepareWife : "xiaowang", name : "laodeng", sex : "male", gf : "xiaoliu", wife : "", divorce : function () { delete this.wife; this.gf = this.PrepareWife; }, getMarried : function () { this.wife = this.gf; }, changePrepareWife : function (someone){ this.PrepareWife = someone; }}Copy the code
2. Object creation method
1. Var obj = {} is called plainObject
2. Constructor
(1) The system’s own constructor new Object
var obj = new Object();
obj.name = 'abc';
obj.sex = 'female';
obj.say = function(){
}
var obj = {
name : ""
}
Copy the code
System-provided: new Object(); Array(); Number(); Boolean(); Date();
(2) Custom
Function Car(){this.name = "BMW"; this.name = "BMW"; this.name = "BMW"; this.height = "1400"; this.lang = "4900"; this.weight = 1000; this.health = 100; this.run = function (){ this.health --; } } var car = new Car(); Var car1 = new Car(); // Not one person, not console. Log (car.run()); console.log(car1.health); console.log(car.health);Copy the code
demo
Achieve their own matching color
function Car(color){
this.color = color;
this.name = "BMW";
this.height = "1400";
this.lang = "4900";
this.weight = 1000;
this.health = 100;
this.run = function (){
this.health --;
}
}
var car = new Car('red');
var car1 = new Car('green');
console.log(car/car1);
Copy the code
function Student(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.grade = 2017;
}
var student = new Student('zhangsan',18,'male');
Copy the code
Matters needing attention
var obj = new Object(){
obj.name = 'abc';
obj.sex = 'female';
obj.say = function(){
}
}
Copy the code
Var obj = {name: ""// colon}Copy the code
The inner workings of constructors
There are three steps that happen with new
1. Implicitly add var this = {} 2 to the body of the function. Execute this. XXX = XXX; 3. Implicitly return this
function Student(name,age,sex) {
//var this = {
// name : ""
// age :
// };
this.name = name;
this.age = age;
this.sex = sex;
this.grade = 2017;
// return this;
}
var student = new Student('zhangsan',18,'male');
Copy the code
function Person(name, height){
// var this = {}
this.name = name;
this.height = height;
this.say = function (){
console.log(this.say);
}
// return this;
}
console.log(new Person('xiaoliu',180).name);
Copy the code
Simulated constructor
function Person(name, height){
var that = {};
that.name = name;
that.height = height;
return that;
}
var person = new Person('xiaowang', 180);
var person1 = new Person('xiaozhang',175);
Copy the code
trivia
function Person(name, height){ var this = {}; this.name = name; this.height = height; this.say = function (){ console.log(this.say); } return {}; Return this; // return this; } var person = new Person('xiaowang', 180); var person1 = new Person('xiaozhang',175); // But return a raw value is not allowedCopy the code
Object. Create (prototype) method
A wrapper class
1. The little knowledge
Primitive values cannot have properties and methods. Only objects can have properties, including objects themselves, arrays, and functions. Numbers are not necessarily raw values. There are two kinds of numbers: raw values Numbers are raw values. There are two kinds of numbers and strings. var num = 123; Var num = new number(123); Also a number, object 123
console.log(num); console.log(num.abc='a'); console.log(num.abc); console.log(num); console.log(num*2); // Become a number, no object attributes, same as string, BooleanCopy the code
Cannot have two original values of an attribute: undefined null
String(); Boolean(); Number();
var num = new Number(123); var str = new String('abcd'); var bol = new Boolean('true'); // undefined and null cannot have properties console.log(num.abc);Copy the code
2. The phenomenon:
Var STR = "abcd"; str.length = 4; Str.abc = 'a'; str.abc = undefined;Copy the code
The original value cannot have properties and methods because it goes through the process of wrapping the class before it can be called
var num = 4; // Wrapping class console.log(num.len = 3); //new Number(4).len = 3; delete // new Number(4).len console.len(num.len); //undefined // num does not have lengthCopy the code
Examination questions
It’s based on a theory: array truncation
var arr = [a,b,c,d];
console.log(arr.length = 2);
console.log(arr);
Copy the code
Into the elder brother of bo
var str = "abcd"; str.length = 2; // new String('abcd').length = 2; delete console.log(str); //abcdCopy the code
variant
var str = "abcd"; str.length = 2; // new String('abcd').length = 2; delete // new String('abcd').length console.log(str.length); / / 4Copy the code
prototype
Definition 1.
A stereotype is a property of the Function object that defines the common ancestor of the object produced by the constructor. Objects generated by this constructor can inherit the properties and methods of the stereotype. Prototypes are also objects.
The constructor produces an object:
// Person. Prototype = {} Person. Prototype name = "hehe"; function Person() { } var person = new Person();Copy the code
Application:
Example 1: Take what you own
Person.prototype.LastName = "Deng"; Person.prototype.say = function(){ console.log('hehe'); } function Person() { // this.LastName = 'ji'; } var person = new person (); var person1 = new Person();Copy the code
Example 2:
Person.prototype.LastName = "Deng";
Person.prototype.say = function(){
console.log('hehe');
}
function Person(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var person = new Person('xuming',30,'male');
Copy the code
2. Extract common attributes.
function Car(color,owner) { this.owner = owner; this.carName = "BMW"; // This. Height = 1400; this.lang = 8900; this.color = color; } var car = new Car('red','prof.ji');Copy the code
To optimize the
Car.prototype.height = 1400;
Car.prototype.lang = 8900;
Car.prototype.carName = "BMW";
function Car(color,owner) {
this.owner = owner;
this.color = color;
}
var car = new Car('red','prof.ji');
var car1 = new Car('green','laodeng');
Copy the code
3. Add, delete, change and check the original form
increase
Person.prototype.lastName = "Deng"; / / shape properties have changed, want to change, is going to call the Person. Prototyoe. LastName function Person (name) {enclosing name = name; } var person = new Person('xuming');Copy the code
console.log(person.lastName="james"); // This is not called modification, this is called adding console.log(person); console.log(person.lastName);Copy the code
delete
console.log(delete person.name); console.log(person.name); console.log(delete person.lastName); console.log(person.lastName); // Delete invalidCopy the code
To optimize the
Car.prototype.height = 1400; Car.prototype.lang = 8900; Car.prototype.carName = "BMW"; Car. Prototype = {height: 1400, lang: 4900, carName: "BMW"}Copy the code
change
2. How does the object view the object’s constructor — > constructor
Function Person(){// constructor: constructor = {constructor: Person } function Car(){ } var car = new Car(); console.log(car.constructor);Copy the code
check
- How do objects view stereotypes – > implicit property proto
function Person(){ } var person = new Person(); // Light purple, implicit naming rule console.log(person);Copy the code
person.prototype.name = 'abc'; function Person(){ } var person = new Person(); // Private attributes: var __pravite console.log(person.__proto__)//__proto__ contains the original formCopy the code
Person.prototype.name = 'abc'; function Person(){ var this = { // __proto__: Person. Prototype}} var perosn = new Person(); console.log(perosn.name);Copy the code
Changing the proto pointer causes the pointer to change
Person.prototype.name = 'abc'; function Person() { // var this = { // // __proto__: Person.prototype // } } var obj = { name: "sunny" } var person = new Person(); Person.__proto__ = obj;Copy the code
Demo 1
Person.prototype.name = "sunny"; function Person() { } var person = new Person(); Person.prototype.name = "cherry"; person.name; Prototype: Sunny, cherry, cherryCopy the code
Demo 2
Person.prototype.name = "sunny"; function Person() { } Person.prototype.name = "cherry"; var person = new Person(); console.log(person.name); CherryCopy the code
Demo 3
Person.prototype.name = "sunny"; function Person() { } var person = new Person(); Person.prototype = { name : "cherry" } person.name; Sunny. The original value is changed on the basis of the original, this time is the original shape changed, for a new objectCopy the code
Simplification: Cross-assignment of reference values
var obj = {name : "a"};
var obj1 = obj;
obj = {name : "b"};
obj1:a,obj:b
Copy the code
Person.Prototype.name = "sunny"; Function Person() {//var this = {__proto__:Person. Prototype}}// var Person = new Person(); Person. Prototype = {name: 'cherry'} // prototype = {name:"a"}; // __proto__ = Person.Prototype; // Person.Prototype = {name:"b"};Copy the code
Demonstrate 4
Person.prototype.name = "sunny"; function Person() { } Person.prototype = { name: "cherry" } var person = new Person(); person.name; Answer: Cherry Function Person() {var this = __proto__ person.prototype} function Person() {var this = __proto__ person.prototype} Re - access: cover the followingCopy the code
Prototype chain introduction
Grand.prototype.LastName = "Deng"; function Gand(){ } var grand = new Grand(); Father.prototype = grand; function Father(){ this.name = "xuming"; } var father = new Father(); Son.prototype = father; function Son(){ this.hobbit = "somke"; } var son = new Son(); console.log(son.hobbit); console.log(son.name); // Follow the chain to console.log(son.tostring); Grand.proto__ = object. prototype Console. log(object.prototype); console.log(Object.prototype.__proto__); Proto is gone, so is the terminalCopy the code
Prototype chain
How to form a prototype chain?
1. Add, delete, modify and check the attributes on the prototype chain
Add, delete, modify: only I have permission, descendants did not
console.log(delete Father.prototype.n); / / deleteCopy the code
Special case: reference value call modification
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'xuming';
this.fortune = {
card1 : 'visa'
}
}
var father = new Father();
Son.prototype = father;
function Son(){
this.hobbit = "somoke";
}
var son = new Son();
Copy the code
console.log(son.fortune);
son.fortune = 200;
console.log(son);
console.log(father.fortune);
son.fortune.card2 = 'master';
cons.log(father);
Copy the code
demo
Grand.prototype.LastName = "Deng";
function Grand(){
}
var grand = new Grand();
Father.prototype = grand;
function Father(){
this.name = "xuming";
this.forture = {
card1 : 'visa'
};
this.num = 100;
}
var father = new Father();
Son.prototype = father;
function Son(){
this.hobbit = "smoke";
}
var son = new Son();
Copy the code
console.log(son.num++); 100 console.log(father); 100 console.log(son.num); 101Copy the code
demo
Person.prototype = { name : "a", sayName : function(){ console.log(this.name); } } function Person(){ } var person = new Person(); // ACopy the code
Person.prototype = {
name : "a",
sayName : function(){
console.log(this.name);
}
}
function Person(){
this.name = "b";
}
var person = new Person();
Copy the code
Person.sayname (); a.sayname (); person.sayname (); Person called, b if person.prototype.sayname (); a
Person.prototype = {
height : 100
}
function Person(){
this.eat = function(){
this.height ++;
}
}
var person = new Person();
Copy the code
console.log(person.eat); person.eat(); console.log(person.eat); // Default return: undefined to view the code to writeCopy the code
Company specification: Arrays, objects are created with literals
var obj = {}; Var obj1 = new Object(); var obj1 = new Object(); Var obj = {}; We have a new Object() inside, so we write the Object literalCopy the code
Most objects eventually inherit from Object.prototype
(选 题真题) exception: because object.create
console.log(Object.create()); Console. log(object.create (null));Copy the code
Object. Create can also create objects
// var obj = Object; var obj = {name : "sunny", age : 123}; var obj1 = Object.create(obj); // Obj1 becomes the object. The original form of obj1 is obj, so obj1.name is obj.nameCopy the code
Person.prototype.name = "sunny";
function Person() {
}
var person = Object.create(Person.prototype);
Copy the code
2. About the toString:
Only undefined and null cannot call toString numbers because 123.toString() is accessed layer by layer through the wrapper class; Undefined has no wrapper class and is a primitive value that cannot be called
console.log(undefined.toString); console.log(null.toString); obj.__proto__ = { name: sunny}; console.log(obj.name); // It doesn't workCopy the code
ToString returns different returns for each variable and each attribute value
var num = 123; console.log(num.toString); // string console.log(123.tostring); // identify the float typeCopy the code
The phenomenon of
var obj = {}; obj.toString(); ---->[object Object]Copy the code
why
var num = 123; // num.toString(); -->new Number(num).toString(); Number.prototype.toString = function (){ } // Number.prototype.__proto__ = Object.prototypeCopy the code
Rewrite pen test: write a method rewrite form, write a system with the same name, different functions
// Object.prototype.toString = function (){
// }
Person.prototype = {
toString : function () {
return 'hehhe';
}
}
function Person () {
}
var Person = new Person();
Copy the code
3. The little bug
The console. The log (0.4 * 100); //js accuracy is not console.log(math.ceil (123.234)); // round up console.log(math.floor (123.99999)); / /Copy the code
Randomly generate 0-100 random numbers
Math.random(); For (var I = 0; i < 10; i++){ var num = Math.random().toFixed(2)*100; console.log(num); // there will be a deviation}Copy the code
Solution: first *100 and then round
for(var i = 0; i < 10; i++){ var num = Math.floor(Math.random() * 100); console.log(num); } // Summary: the normal calculation range: 16 before and 16 after the decimal pointCopy the code
call/apply Forbid to
1.call
Function to change the this pointer. Borrow other people’s function to achieve their own function distinction, the form of parameters passed behind different. Call needs to pass arguments as many arguments as the parameters apply needs to pass arguments
function test(){ } test()===test.call(); // The default is implicitCopy the code
You can pass things in call
function Person(name, age){ this.name = name; this.age = age } var person = new Person('deng',100); var obj = { } // Person.call(obj); Person.call(obj,'cheng',300); Person.call(obj,'cheng',300);Copy the code
Enterprise development
Function Person(name, age, sex) {this.name = name; function Person(name, age, sex) {this.name = name; this.age = age; this.sex = sex; } function Student(name, age, sex, tel, grade){ this.name = name; this.age = age; this.sex = sex; this.tel = tel; this.grade = grade; Function Person(name, age, sex) {this.name = name; this.age = age; this.sex = sex; } function Student(name, age, sex, tel, grade){ // var this = {name : "", age : "",sex : ""} Person.call(this, name, age, sex); this.tel = tel; this.grade = grade; } var student = new student ('sunny',123,'male',139,2017);Copy the code
Building cars, for example,
function Wheel(wheelSize,style) { this.style = style; this.wheelSize = wheelSize; } function Sit(c,sitColor) { this.c = c; this.sitColor = sitColor; } function Model(height,width,len) { this.height = height; this.width = width; this.len = len; } function Car(wheelSize, style, c, sitColor, height, width, len) { Wheel.call(this, wheelSize,style); Sit.call(this,c,sitColor); Model.call(this, height, width, len); } var car = new car (100,' black ','red',1800,1900,4900);Copy the code
2. Apply:
Apply can only pass an array of arguments wheel. apply(this, [wheelSize,style]);
Conclusion:
Call: The argument needs to be passed in according to the number of parameters
Apply: Need to pass a arguments
Assignment: Ebook JS design patterns on pages 0-35
Pen try: use friend 2017 school recruit front end
Succession history
1. Traditional form
Too many inherited useless attributes
Grand.prototype.lastName = "Ji"; function Grand() { } var grand = new Grand(); Father.prototype = grand; function Father() { this.name = "hehe"; } var father = new Father(); Son.prototype = father; function Son() { } var son = new Son(); // a series of succession from beginning to end, resulting in the succession of those who do not want to continueCopy the code
2. Borrow constructors
You can’t inherit a prototype that borrows a constructor that takes one more function each time it actually wastes efficiency
function Person(name,age,sex){ this.name = name; this.age = age; this.sex = sex; } function Student(name, age,sex, grade) {Person. Call (this,name,age,sex); this.grade = grade; } var student = new Student();Copy the code
3. Share prototypes
You can’t just change your prototype
Father.prototype.lastName = "Deng"; Function Father(){// Father(){function Son(){}Copy the code
Implementation method
-
Prototype chain
Var father = function Son(); 4. 0. How to Lose weight
Father.prototype.lastName = "Deng";
function Father() {
}
function Son() {
}
Son.prototype = Father.prototype
var son = new Son();
var father = new Father();
Copy the code
Abstracted as a function
Father.prototype.lastName = "Deng"; function Father() { } function Son() { } function inherit(Target, Origin) { Target.prototype = Origin.prototype; } inherit(Son, Father); var son = new Son(); //son.LastName = "Deng";Copy the code
To inherit before using, son.lastname refers to the original space
Father.prototype.lastName = "Deng"; function Father() { } function Son() { } function inherit(Target, Origin) { Target.prototype = Origin.prototype; } var son = new Son(); inherit(Son, Father); Son. lastName = undefinedCopy the code
Inadequate:
Son adds an attribute to himself, which is convenient for the subsequent production of the object to use. It can not be personalized implementation, inheritance, but impact
Father.prototype.lastName = "Deng"; function Father(){ } function Son(){ } function inherit(Target, Origin){ Target.prototype = Origin.prototype; } inherit(Son, Father); Son.prototype.sex = "male"; Var son = new son (); var son = new son (); var father = new Father(); // To achieve: want to inherit but not influence each otherCopy the code
4. Holy Grail mode
Through the prototype chain
function inherit(Target, Origin) {
function F(){};
F.prototype = Origin.prototype;
Target.prototype = new F();
}
Father.prototype.lastName = "Deng";
function Father(){
}
function Son() {
}
inherit(Son,Father);
var son = new Son;
var father = new Father();
console.log(Son.prototype.sex = "male");
console.log(son.sex);
console.log(father.sex);
console.log(Father.prototype);
Copy the code
Constructor should point to the constructor, however, son.constructor = ƒ Father()???? What’s going on?
The system has a built-in property called constructor, which by default points to its constructor
Son. __proto__ - > new F (.) __proto__ - > Father. The prototype / / points to the disorderCopy the code
Achieve inheritance: Must have the Holy Grail mode
function inherit(Target, Origin){ function F(){}; F.prototype = Origin.prototype; Target.prototype = new F(); Target.prototype.constructor = Target; Target.prototype.uber = Origin.prototype; / / super parent: super class} Father. The prototype. The lastName = "Deng"; function Father(){ } function Son(){ } inherit(Son, Father); var son = new Son(); var father = new Father();Copy the code
Upside down
F.prototype = Origin.prototype; Target.prototype = new F(); // Do not reverse, must change the original shape before newCopy the code
Kind of yahoo!
What closures do: Encapsulate and privatize properties
function Deng(name, wife){
var prepareWife = "xiaozhang";
this.name = name;
this.wife = wife;
this.divorce = function(){
this.wife = prepareWife;
}
this.changePrepareWife = function(target){
prepareWife = target;
}
this.sayPreparewife = function(){
console.log(prepareWife);
}
}
var deng = new Deng('deng','xiaoliu');
Copy the code
console.log(deng.sayPreparewife()); Console. log(deng.preparewife)// If you can't see it directly, privatize the variableCopy the code
F becomes the privatization variable
var inherit = (function(){ var F = function(){}; Return function(Target,Origin){f.protoType = origine.prototype; Target.prototype = new F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin.prototype; }} ());Copy the code
Discrete Mathematics (important) — >CS majors (Computer majors) ,,,, Probability theory, artificial Intelligence
The namespace
Is the object
Manage variables, prevent global pollution, suitable for modular development
One page, multiple people collaborate, merge conflicts
1. The old way: namespaces
var org = {
department1 : {
jicheng : {
name : "abc";
age : 123;
},
xuming : {
}
},
department2 : {
zhangsan : {
},
lisi : {
}
}
}
var jicheng = org.department1.jicheng;
jicheng.name;
Copy the code
2. New approach: Privatize variables with closures
webpack
Closure (privatize variables) + execute the function immediately
var name = "bac";
var init = (function(){
var name = "abc";
function callName(){
console.log(name);
}
return function(){
callName();
}
}())
init();
Copy the code
Collaboration is not in conflict
var name = "bac";
var init = (function(){
var name = "abc";
function callName(){
console.log(name);
}
return function(){
callName();
}
}())
var initDeng = (function(){
var name = 123;
function callName(){
console.log(name);
}
return function(){
callName();
}
}())
Copy the code
Obj.eat ().smoke().drink().eat().sleep();
$('div').css('background-color','red').width(100).height(100).
html(123).css('position','absolute').
css('left','100px').css('top','100px');
Copy the code
Simulate jQuery to implement continuous call methods
var deng = { smoke : function () { console.log('Smoking... xuan cool!!! '); }, drink : function () { console.log('Drinking... good'); }, perm : function(){ console.log('perming... cool'); } } deng.smoke(); deng.drink(); deng.perm(); // How to implement JQ like continuous callCopy the code
Why not call it continuously
console.log('Smoking... xuan cool!!! '); // return undefined;Copy the code
Var deng = {smoke: function () {console.log(‘Smoking… xuan cool!!! ‘); return this; }, drink : function () { console.log(‘Drinking… good’); return this; }, perm : function(){ console.log(‘perming… cool’); return this; } } deng.smoke().drink().perm().smoke().drink();
Num = num; num = numCopy the code
var deng = { wife1 : {name : “xiaoliu”}, wife2 : {name : “xiaozhang”}, wife3 : {name : “xiaowang”}, wife4 : {name : “xiaoli”}, sayWife : function(num) { switch(num) { case 1: return this.wife1; }}}
Simplify the above code: concatenate variable attribute namesCopy the code
var obj = { name : “abc” }
**obj.name---->obj['name']; ** will be converted to square brackets inside, so so square brackets can be string concatenationCopy the code
var deng = { wife1 : {name : “xiaoliu”}, wife2 : {name : “xiaozhang”}, wife3 : {name : “xiaowang”}, wife4 : {name : “xiaoli”}, sayWife : function(num) { switch(num) { case 1: return this[‘wife’ + num]; }} console.log(deng.saywife (1));
Loop data group traversal: want to know the information of ten people, know one by oneCopy the code
Var arr =,3,3,4,5,6,7,8,9 [1]; Enumeration for(var I = 0; i < arr.length; i++){ console.log(arr[i]); / / traverse}
What if you want to find (traverse) the object?Copy the code
var obj = { name : “123”, age : 123, sex : “male”, height : 180, weight : 75 //prop:123 } for(var prop in obj){ console.log(obj.prop); // obj. Prop –>obj[‘prop’] is a property}
Truth:Copy the code
var obj = { name : ’13’, age : 123, sex : “male”, height : 180, weight : 178, proto : { lastName : ————hasOwnProperty}} for(var prop in obj) {console.log(obj[prop]); //console.log(obj[‘prop’]); // Obj. Prop is the same as obj.
Implementation of obj1 property +1 returns error demonstrationCopy the code
var obj1 = { a : 123, b : 234, c : 456 } var key; For (key in obj1) {obj1.key ++; }
## 1. HasOwnProperty () {hasOwnProperty () {hasOwnProperty ()Copy the code
var obj = { name : ’13’, age : 123, sex : “male”, height : 180, weight : 178, proto : { lastName : “deng” } } for(var prop in obj) { if(obj.hasOwnProperty(prop)){ console.log(obj[prop]); }}
Their set must be able to print, the system set must notCopy the code
var obj = { name : ’13’, age : 123, sex : “male”, height : 180, weight : 178, proto : { lastName : “deng”, proto : Object. Prototype // Once extended to the top of the prototype chain, the top will not be printed}}
## 2.in is similar to hasOwnPropertyCopy the code
var obj = { name : ’13’, age : 123, sex : “male”, height : 180, weight : 178, proto : { lastName : Log (‘height’ in obj)//height is called console.log(‘height’ in obj concole.log(‘lastName’ in obj)
HasOwnProperty () : hasOwnProperty () : hasOwnProperty () : hasOwnProperty () : hasOwnPropertyCopy the code
function Person(){ } var person = new Person(); var obj = {}; // A is the console.log(person instanceof person) constructed by the B constructor; // —->ture
See if there is A prototype of B on the prototype chain of object A (key point)Copy the code
console.log(person instanceof Object); —->ture console.log([] instanceof Array); —->ture console.log([] instanceof Object); —->ture console.log(person instanceof Array); —->false console.log(obj instanceof Person); —->false
Problem solved > Determine whether a variable is an array or an objectCopy the code
Typeof ([]) “object” typeof ({}) “object” / / demand: var arr = [] | | {};
The first method:Copy the code
var obj = {}; //var obj = []; Obj. Constructor //
The second method:Copy the code
[] instanceof Array //true var obj = {}; obj instanceof Array //false
The third method: toStringCopy the code
Object.prototype.toString.call([]); / / Object. The prototype. ToString = function () {/ / who calls, this is who / / identify this: / / / / return the corresponding results} / / obj. The toString (); // call.toString(); Object.prototype.toString.call([]); / / array can replace this Object. The prototype. ToString. Call (123); Object.prototype.toString.call({}); // Distinguish between arrays and objects
Console verificationCopy the code
Object.prototype.toString.call([]); “[object Array]” Object.prototype.toString.call({}) “[object Object]” Object.prototype.toString.call(123); “[object Number]”
# this ## 1. This -- > windowCopy the code
function test(c) { //var this = Object.create(test.prototype); {// prototype: test.prototype} var a = 1; The function b () {}} / / AO {/ / the arguments: [1], the / / / / at this: Windows, / / own / / c: 1, / / a: undefined, / / b: function() {} //} test(1); new test(); // New causes this pointer to change and is no longer window
validationCopy the code
function test(){ console.log(this); } test();
## 2. This -- > window in the global scopeCopy the code
console.log(window);
Call /apply can change this to refer to ## 4.obj.f(); This in f() refers to obj). This refers to whoever calls this method. If no one calls this method, this is the windowCopy the code
Var obj = {a: function () {console.log(this.name)}, name: ‘ABC’} obj (); / / obj calls
## 5. The condition is false: 0, false, null, undefined, undefined. The function declaration is written in the operator, which is true, but the function declaration placed in the operator is not found at execution time. In addition, typeof for undeclared variables does not return an error, and undefined this is returnedCopy the code
var name = “222”; var a = { name : “111”, say : function(){ console.log(this.name); } } var fun = a.say; Var b = {name: “333”, say: {var b = {name: “333”, say: {var b = {name: “333”, say: function(fun){ //this—->b fun(); This –>window,222}} b.sage (a.sage); this– >window,222}} b.sage (a.sage); //a.say– is the body of the function above, 222 b.say = a.say; // copy the above function to b.say(instead of b.say) b.say(); / / 333
# arguments
> arguments.callee
> func.caller
arguments
Copy the code
function test(){ console.log(arguments.callee); } test(); // Return its own function body
Application:Copy the code
var num = (function(n){ if(n == 1) { return 1; } return n* factorial (n-1); } (100))
Perform the factorial of a function immediately: can only be done with CalleeCopy the code
var num = (function(n){ if(n == 1) { return 1; } return n*arguments.callee(n-1); } (100))
Inside that function, it prints whateverCopy the code
function test(){ console.log(arguments.callee); function demo(){ console.log(arguments.callee); } demo(); }
Caller: In which environment is demo invokedCopy the code
function test () { demo(); } function demo() { console.log(demo.caller); } test();
1. Shallow cloningCopy the code
var obj = { name : ‘abc’, age : 123, sex : ‘female’ } var obj1 = {} function clone(origin,target){ for(var prop in origin){ target[prop] = origin[prop]; } } clone(obj,obj1); // Print obj1 to show that it has been copied
Implement fault tolerance:Copy the code
var obj = { name : ‘abc’, age : 123, sex : ‘female’ } var obj1 = {} function clone(origin,target){ var target = target || {}; for(var prop in origin){ target[prop] = origin[prop]; } return target; } clone(obj,obj1);
The original value is fine, but the reference value is copied:Copy the code
var obj = { name : ‘abc’, age : 123, sex : ‘female’, card : [‘visa’, ‘unionpay’] } var obj1 = {} function clone(origin,target){ var target = target || {}; for(var prop in origin){ target[prop] = origin[prop]; } return target; } clone(obj,obj1);
## 2. Deep clone two people, clone, only consider the array of reference values, object core: distinguish arrays and objectsCopy the code
Var obj = {name: ‘ABC ‘, age: 123, sex: ‘female’, card: [‘visa’,’unionpay’,[1,2]]} var obj1 = {card: [obj.card[0],obj.card[1],[]] } clone(obj, obj1);
Copy the code
var obj = { name : ‘abc’, age : 123, card : [‘visa’, ‘master’], wife : { name : “bcd”, son : { name : }} var obj1 = {name: obj. Name, age: 123, card: [] [obj.card[0],obj.card[1]], wife: {name: “BCD “, son: {name:” BCD “, son:}}
Object traversal for(var prop in obj) Traversal not only traversal objects, but also traversal groupsCopy the code
var arr = [‘a’,’b’,’c’] for(var prop in arr) { arr[prop] }
Typeof () : null typeof() : null typeof() : null There are three ways to use arrays or objects: Instanceof toString constructor is recommended because the other two have minor problems and do not encounter parent-child domains: [] instanceof Array -- >false should true 3. Create corresponding arrays and objectsCopy the code
/ / a recursive function deepClone (origin, target) {var target = target | | {}; / / fault-tolerant toStr = Object. The prototype. ToString, arrStr = “[Object Array]”. / / than}
Code implementationCopy the code
var obj = { name : ‘abc’, age : 123, card : [‘visa’, ‘master’], wife : { name : “bcd”, son : { name : “aaa” } } } var obj1 = { } function deepClone(origin,target) { var target = target || {}; / / fault-tolerant toStr = Object. The prototype. ToString, arrStr = “[Object Array]”. For (var prop in origin) {if(origine.hasownProperty (prop)) {// Prevent typeof(origin[prop]) == ‘object’) { if(toStr.call(origin[prop]) == arrStr) { target[prop] = []; }else{ target[prop] = {}; } deepClone(origin[prop],target[prop]); Else {target[prop] = origin[prop]; } } } return target; }
To optimize theCopy the code
function print(){ function deepClone(origin, target){ var target = target || {}, toStr = Object.prototype.toString, arrStr = “[object Array]”; For (var prop in origin) {if(origine.hasownProperty (prop)) {//null problem if(origin[prop]! = = “null” && typeof (origin [prop]) = = ‘object’) {/ / absolutely is not equal to, If (tostr.call (origin[prop]) == arrStr) {target[prop] == []; }else{ target[prop] = {}; } deepClone(origin[prop],target[prop]); }else{ target[prop] = origin[prop]; } } } return target; }
Ternary operators simplify codeCopy the code
function print(){ function deepClone(origin, target){ var target = target || {}, toStr = Object.prototype.toString, arrStr = “[object Array]”; For (var prop in origin) {if(origine.hasownProperty (prop)) {//null problem if(origin[prop]! = = “null” && typeof (origin [prop]) = = ‘object’) {/ / absolutely is not equal to, Target [prop] = (tostr. call(origin[prop]) == arrStr) [] : {}; deepClone(origin[prop],target[prop]); }else{ target[prop] = origin[prop]; } } } return target; }
Var obect.create (); Var obect.create (); Var obect.create (); Var obect.create (); Var obect.create (); Array literals var arr = [];Copy the code
Var arr = [1, 2, 3, 5]; // Sparse array
2.new Array(length/content);
Copy the code
Var arr = new Array(1,2,3,4,5);
The difference betweenCopy the code
var arr = new Array(10); Var arr1 = [10]; Var arr = new Array(10.2); // The length is 10.2
Read and write arraysCopy the code
Arr [num] = XXX; arr[num] = XXX; // Can overflow write, lengthen array
In JS, arrays do not fail even if they do not have the 10th bit, because arrays are the common method for object-based arrays. 7 reverse, change the original array sort, push, pop, shift, unshift, > push to increase the last of the array encapsulated push ()Copy the code
Var arr = [1, 2, 3]; Array.prototype.push = function (){array.prototype.push = function (){array.prototype.push = function (){array.prototype.push = function (){array.prototype.push = function (){ i < arguments.length; i++) { this[this.length] = arguments[i]; } return this.length; }
> pop: cut out the last bit of the array arr.pop(); > shift: Reverse: reverse > sort arr.sort(); reverse: reverse > sort arr.sort(); Var arr = [1,2,10,2,4,5]; var arr = [1,2,10, 5]; Cannot implement the desired sort implement sort :(bubble sort) 1. Must have two parameters 2. Look at the return value (1) return a negative value, the first number before (2) is positive, the following number before (3) is 0, do not moveCopy the code
Var arr =,2,10,2,4,5 [1]; arr.sort(function (a, b) { if(a > b) { return 1; }else{ return -1; }});
Simplify the codeCopy the code
arr.sort(function (a, b) { if(a – b > 0) { return a – b; }else{ return a – b; }});
In the endCopy the code
arr.sort(function (a, b) { return a – b; //return b – a; / / descending});
Give an ordered array out of orderCopy the code
Math. The random () returns (0, 1) random number / / var arr =,2,3,4,5,6,7 [1]; // arr.sort(function () {// return math.random () -0.5; });
Object age sortCopy the code
var cheng = { name : “cheng”, age : 18, sex : ‘male’, face : “handsome” } var deng = { name : “deng”, age : 40, sex : undefined, face : “amazing” } var zhang = { name = “zhang”, age = 20, sex = “male” } var arr = [cheng, deng, zhang]; arr.sort(function (a, b) { // if(a.age > b.age) { // return 1; // }else{ // return -1; // } return a.age – b.age; }
String length sortCopy the code
var arr = [‘ac’,’bcd’,’cccc’,’asfsadshilk’,’casuicbniasbnciuas’]; arr.sort(function (a, b){ return a.length – b.length; })
Byte length sortCopy the code
function retBytes(str) { var num = str.length; for(var i = 0; i < str.length; i++){ if(str.charCodeAt(i) > 255){ num ++; } } return num; } var arr = [‘ a deng ‘, ‘ba deng’, ‘cc deng cc’, ‘dumbledore, “residual” deng,’ asdoifqwoeiur ‘, ‘asdf’]. arr.sort(function (a, b){ return retBytes(a)-retBytes(b); })
> splice: sliceCopy the code
Arr.splice (1,2); // arr.splice(1,2); Var arr = [1,1,2,2,3,3]; Arr. Splice,1,0,0,0 (1); Var arr =,2,3,5 [1]; Arr. Splice (3,0,4); Arr. Splice (-1,1); // First to last
-1 is the last; How do I get the second to last of 1Copy the code
splice = function(pos) { pos += pos>0? 0:this.length; / / negative}
Join -- >split,toString > 0. Concat joinCopy the code
Var arr = [6]; Var arr1 =,8,9 [7]; arr.concat(arr1);
> toString turns arrays into strings > SliceCopy the code
Var arr = [6]; Var newArr = arr. Slice (1,3); var newArr = arr. Slice (1) var newArr = arr.slice(-4)//-4+6 bits // 3. No parameters: full interception
> join implements string joinCopy the code
Var arr = [1, 2, 3, 4]; Arr. Join (“-“)// The value must be a string of characters arr = [1-2-3-4];
Word-wrap: break-word! Important; "> < span style =" max-width: 100%Copy the code
var arr = [1-2-3-4]; Arr.split (“3”)// Must be a string
We can use property names to emulate property 2 of arrays. 3. If you force the array to call push, the length property will be expanded according to the position of the length property value.Copy the code
function test() { console.log(arguments); arguments.push(7); } test(1,2,3,4,5,6);
The phenomenon ofCopy the code
/ / complete the basic form of an array of class build var obj = {” 0 “: ‘a’,” 1 “, “b”, “2” : “c”, “length” : 3, “push” : Array.prototype.push } obj.push(‘d’); // Results in length=4 and “3”:d
Class array: objects that can be used as arraysCopy the code
var obj = { “0” : ‘a’, “1” : ‘b’, “2” : ‘c’, “length” : 3, “push” : Array.prototype.push, “splice” : Array.prototype.splice// array.prototype.splice // array.prototype.splice // array.prototype.splice // array.prototype.splice // array.prototype.splice //
Length internal operation:Copy the code
Array.prototype.push = function(target) { this[this.length] = target; this.length ++; } // Array.prototype.push = function(target) {obj[obj.length] = target; obj.length ++; }
Class array to iterate over all the elementsCopy the code
var obj = { “0” : “a”, “1” : “b”, “2” : “c”, name : “abc”, age : 123, length : 3, push : Array.prototype.push, splice : Array.prototype.splice } for(var prop in obj){ console.log(obj[prop]) }
Type Typeof ([])-- Array Typeof ({})-- Object Typeof (function)-- function Typeof (new Number())-- new Object Typeof (123)-- number typeof(123)-- number typeof(123)-- numberCopy the code
function type(target) { var template = { “[object Array]” : “array”, “[object Object]” : “object”, “[object Number]” : “number – object”, “[object Boolean]” : ‘boolean – object’, “[object String]” : ‘string – object’ } if(target === null){ return “null”; } // if(typeof(target) == ‘function’) { // return ‘function’; Else if(typeof(target) == “object”) = {if(typeof(target) == “object”){// array; / / object; / / wrapper class Object. The prototype. ToString var STR = Object. The prototype. ToString. Call (target); return template[str]; }else{// original value return typeof(target); }
Array de-duplication, programming hash hash on the prototype chainCopy the code
Var arr =,1,1,1,2,2,2,2,2,1,1,1,0,0 [1]; Array.prototype.unique = function() { var temp = {}, arr = [], len = this.length; For (var I = 0; i < len; i++){ if(! Temp [this[I]]) {temp[this[I]]; Temp [this[I]] = “ABC “; arr.push(this[i]); } } return arr; }
# Ternary operator form: judgment statement? If true, execute and return the result: If false, execute and return the result The trinary operator is a simplified version of if(){... }else{} Yes: No and returns a valueCopy the code
var num = 1 > 0 ? 2 + 2:1 + 1; var num = 1 > 0 ? “9” (” 10 “>? 1:0) : 2;
# try... Catch try{} Catch (e) {} Finally {}Copy the code
//try… catch try{ console.log(‘a’); console.log(b); console.log(‘c’); } catch(e) { } console.log(‘d’); // If an error occurs in a try, the code in the try will not be executed, and the AD will be printed
About the catchCopy the code
try{ console.log(‘a’); console.log(b); console.log(‘c’); }catch(e){//error error.message error.name —> error console.log(e.name + ” : ” + e.message);
} console.log(‘d’);
A small problemCopy the code
try{ console.log(‘a’); console.log(b); console.log(c); }catch(e){console.log(e.name + “:” + e.message);}catch(e){console.log(e.name + “:” + e.message); } console.log(‘d’);
The six values of error.name correspond to the following information: EvalError: the use of eval() is inconsistent with the definition.RangeError: a value is out of bounds.ReferenceError: an invalid or unrecognized value. TypeError: TypeError: operand TypeError; URIError: URI handler error; Es5.0 +**es5.0 +** ES5.0 +**es5.0 +**es5.0 +**es5.0 +**es5.0 +**es5.0 +**es5.0 Otherwise, ES3.0 "Use Strict" is no longer compatible with some irregular syntax of ES3. Use the new ES5 specification. Demo1: ES5 does not allow arguments.calleeCopy the code
Function test() {console.log(arguments.callee); function test() {console.log(arguments. } test();
demo2
Copy the code
function demo() { console.log(arguments.callee); } demo(); //es3.0 function test() {“use strict”// internal es5.0 console.log(arguments.callee); } test();
Two usages: Global strict mode A strict mode within a local function (recommended) is a string that does not affect browsers that do not support strict mode: With (){} with can change the scope chain, with(obj) obj as the top AOCopy the code
var obj = { name : “obj” } var name = ‘window’; function test() { var name = ‘scope’; With (obj) {// If an object is added to with, with(obj) treats the object as the top of the scope chain of the body of code to execute with; console.log(name); } } test();
demoCopy the code
var obj = { name:”obj”, age:234 } var name = “window”; function test(){ var age = 123; var name = “scope”; with(obj){ console.log(name); //obj console.log(age); //234 } } test();
With simplifies codeCopy the code
var org = { dp1 : { jc : { name : ‘abc’, age : 123 }, deng : { name : “xiaodneg”, age : 234 } }, dp2 : {}} with(org.dp1.jc) {// Directly access console.log(name) in org.dp1.jc; }
Application: Document is also an objectCopy the code
document{ write : function () {} } with(document) { write(‘a’); }
Is not supported with the arguments. The callee, func. Caller, variable assignment must be declared before the local this must be the assignment, (Person) call (null/undefined) anything assignment), refused to repeat properties and parametersCopy the code
“use strict” function test(){ console.log(this); //undefined } test();
The newCopy the code
“use strict” function Test(){ console.log(this); } new Test();
Precompile In ES5 strict mode this does not point to window, it does not point to (null), this must be assigned, what is assignedCopy the code
“use strict” function Test(){ console.log(this); } Test.call({});
Assign a value of 123Copy the code
“use strict” function Test(){ console.log(this); } Test.call(123);
123 is the raw value :ES3 becomes the wrapper classCopy the code
function Test(){ console.log(this); } Test.call(123);
In strict mode, globally, this refers to the windowCopy the code
“use strict” console.log(this);
Es5 refuses to duplicate the ** attribute and parameter **. Duplicate attributes and arguments are not reported in ES3Copy the code
function test (name , name){ console.log(name); } / / test (1, 2); //test(2);
Parameter errorCopy the code
“use strict” function test (name , name){ console.log(name); } the test (1, 2);
Property does not report errorsCopy the code
Var obj={name:’112′, name:’111′} test(1,2);
Eval: 0.es3 cannot be eval(); Eval can execute stringsCopy the code
“use strict”; var a = 123; eval(‘console.log(a)’); // The string is executed in eval
Why not use with(); With can change the scope chain, change the scope chain, will reduce the efficiency The youth online < https://www.yuque.com/docs/share/7773dc1a-cd7d-4bf2-9b5a-170194ad9a56 > MDN website internal documentCopy the code