当前位置:网站首页>JS__ Prototype, prototype chain, call/apply__ Duyi
JS__ Prototype, prototype chain, call/apply__ Duyi
2022-06-25 20:57:00 【Leap soil and tea】
Prototype
- Definition : The prototype is function An attribute of an object , It defines the common ancestor of the object created by the constructor . The object produced by the constructor , You can inherit the properties and methods of the prototype . Prototypes are also objects .
//Person.prototype -- Prototype
//Person.prototype = {} It's an ancestor
Person.prototype.Lastname = "Deng";
Person.prototype.say = function(){
// Method
console.log('hehe');
}
function Person(name, age, sex){
this.name = name;
this.age = age;
this.sex = sex;
}
var person = new Person('xuming', 35, 'male');
var person1 = new Person();
//>person.LastName <"Deng"
- Use prototype features and concepts , Common attributes can be extracted .
// Extract the public , Put it in the prototype
Car.prototype = {
height : 1400,
lang : 4900,
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');
//car Car{owner: "prof.ji", color: "red"}
//car1 Car{owner: "laodeng", color: "green"}
- How do objects view stereotypes – > Implicit attribute __proto__
Person.prototype.lastName = "Deng";
function Person(name){
this.name = name;
}
var person = new Person('xuming');
person.lastName = "James";// Prototype properties cannot be modified through objects , Here is to add attributes
//{name: "xuming", lastName: "James"}
--------------- Split line ---------------
Person.prototype.name = 'abc';
function Person() {
//var this = {
// __proto__ : Person.prototype Connecting objects and prototypes , Prototype of storage object
//};
}
var obj = {
name : "sunny";
}
var person = new Person();
person.__proto__ = obj;
//Object{name : "sunny"}
--------------- Split line ---------------
Person.prototype.name = 'sunny';
function Person(){
//var this = {__proto__ : Person.prototype}
}
var person = new Person();
Person.prototype = {
name : 'cherry';
}
//var obj = {};
//var obj1 = obj;
//obj = {name : "b"}; Change rooms
Person.prototype = {
name : "a"};
__proto__ = Person.prototype;
Persoon.prototype = {
name : "b"};
--------------- Split line ---------------
//new After that, it will generate var this = {__proto__ : Person.prototype}
Person.prototype.name = 'sunny';
function Person(){
//var this = {__proto__ : Person.prototype}
}
Person.prototype = {
name : 'cherry';
}
var person = new Person();
//Person.prototype = {name : "a"};
//Persoon.prototype = {name : "b"};
//__proto__ = Person.prototype;
Change of prototype :prototype. attribute = New properties
Check the prototype :prototype. attribute
Deletion of prototype : You can't find the prototype by looking for properties
- Object how to view the constructor of the object – > constructor
function Person() {
}
Car.prototype = {
constructor : Person
}//car.constructor You can change it manually
function Car() {
}
var car = new Car();
//car.constructor Constructors Return constructor , Inheritance is prototype Constructor
Prototype chain
Definition and Usage
When trying to get the properties of an object , If the object itself does not have this property , Then it will go to its constructor ’prototype’ Find... In properties .
Add a prototype and a prototype to the prototype , Connect the prototype into a chain , The access order is in the order of the chain , It's called the prototype chain .
The connection point of the prototype chain is __proto__, Check from near to far .
//Grand.prototype.__proto__ = Object.prototype
//Object.prototype Is the final prototype of all objects
Grand.prototype.lastName = "Deng";
function Grand() {
}
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'xuming';
this.fortune = {
// Method
card1 : 'visa';
}
this.num = 100;
}
var father = new Father();
Son.prototype = father;
function Son() {
this.hobbit = "smoke";
}
var son = new Son();
//son.toString You can visit , return Object Of toString
son.fortune = 200;//father.fortune unchanged , Cannot assign or modify
son.fortune.card2 = 'master';//ok Reference value fortune Self modification , Modification of the call
son.num ++;//son.num 101 father.num 100
Addition, deletion, modification and query of attributes on the prototype chain
View the properties : Check from near to far , All the way to the end of the prototype chain , If there is no terminal, it is OK undefined
Delete attribute : Only self delete
Modify properties : Only self modification , Can not be modified by assignment , You can call to modify
//a.sayName() sayName Inside this The point is , Who called this method ,this Just point to who
Person.prototype = {
name : "a",
sayName : function () {
// Method
console.log(this.name);
}
}
function Person () {
this.name = "b";
}
var person = new Person();
--------------- Split line ---------------
Person.prototype = {
height : 100
}
function Person () {
this.eat = function () {
// Method
this.height ++;
}
}
var person = new Person();
person.eat
//{height: 101}
person.__proto__
//{height: 100}
Object Definition and Usage
Object It's a constructor ,Object.create( Prototype ) You can also construct objects
var obj = {
}; --> amount to new Object()// Array /null Writing norms
//var obj1 = new Object();
//obj1.__proto__ ---> Object.prototype
Person.prototype = {
} --> Object.prototype
function Person() {
}
grammar :Object.create( Prototype )
//var obj = Object.create( Prototype );
var obj = {
name : "sunny", age : 123};
var obj1 = Object.create(obj);
obj1.name --> obj.name
--------------- Split line ---------------
Person.prototype.name = "sunny";
function Person() {
}
var person = Object.create(Person.prototype);
Most objects will eventually inherit from Object.prototype
Object.prototype It's a terminal ,Object.create(null) The exception is
var obj = Object.create(null);// It's the object , There is no prototype , No, __proto__
// The prototype added by myself __proto__ of no avail
//Object.create( Array );ok
.toString() Method
Object.prototype On itself contains toString Method , But the output form is "[object Xxxxx]"
Why numbers , character string , Array , Boolean output forms are different ?
Take numbers for example , Even though Number.prototype.__ proto__ = Object.prototype. but Number.prototype There are rewritten toString Method , It doesn't call Object.prototype In its own way . Again :
String.prototype There are rewritten toString Method
Array.prototype There are rewritten toString Method
Boolean.prototype There are rewritten toString Method
123.toString();// Will report a mistake , First, it is recognized as floating point type
var num = 123;
num.toString(); // return "123"
var str = 'abc';
str.toString(); // return "abc"
var arr = [1,2];
arr.toString(); // return "1,2"
var obj = {
};
obj.toString(); // return "[object Object]"
Object.prototype.toString.call(123); --> [object Number]
//123 Call directly Object.toString(), Do not call override methods
rewrite , Same name , Different methods , Cover Object.toString()
Object.prototype.toString = function() {
return 'haha';
}
Person.prototype = {
//toString : function () {
//return 'hehe';
//}
}
function Person() {
}
var person = new Person();
//person.toString() --> haha
--------------- Split line ---------------
var obj = Object.create(null);
document.write(obj);// call toString Method , There is no prototype , You can't toString, Report errors
obj.toString = function () {
return ' Lao Deng is in good health ';
}
document.write(obj);// Lao Deng is in good health
toFixed() Keep two decimal places (JS Inaccuracy )
Math.ceil(123.234) Rounding up
Math.floor(123.999999) Rounding down
Math.random() A random number between zero and one
The range that can be normally calculated , Before the decimal point 16 position , after 16 position
for(var i = 0; i < 10; i++){
var num = Math.floor(Math.random() * 100);
console.log(num);
}
call/apply
effect , change this Point to
function Person(name, age) {
//this == obj obj Instead of this
obj.name = name;
obj.age = age;
}
var person = new Person('deng', 100);
var obj = {
}
Person.call(obj, 'cheng', 300);
// The first parameter will change this The direction of ( Point to the incoming object ), Parameters after the second bit correspond to formal parameters
//obj --> {name: "cheng", age: 300}
// Use other people's methods to realize their own functions
//function test() {
}
//test(); ---> test.call();
--------------- Split line ---------------
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);
--------------- Split line ---------------
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, ' Fancy ', ' Genuine leather ', 'red', 1800, 1900, 4900);
difference , The parameters passed later have different forms
call You need to pass in arguments according to the number of parameters
apply Need to pass a arguments,apply Only arrays can be passed
function Car(wheelSize, style, c, sitColor, height, width, len) {
Wheel.apply(this, [wheelSize, style]);
Sit.apply(this, [c, sitColor]);
Model.apply(this, [height, width, len]);
}
Homework :
1. function test() and new test() What are the results of ?
var a = 5;
function test() {
a = 0;
alert(a);//0
alert(this.a);//5
var a;
alert(a);//0
}
test();
3.
a = 100;
function demo(e) {
function e() {
}
arguments[0] = 2;
document.write(e);
if(a) {
var b = 123;
function c() {
// Pigs can make it
}
}
var c;
a = 10;
var a;
document.write(b);
f = 123;
document.write(c);
document.write(a);
}
var a;
demo(1);
document.write(a);
document.write(f);
4.
var str = "abc";
str += 1;
var test = typeof(str);//"string"
if(test.length == 6) {
test.sign = "typeof The return result of may be String";
}
document.write(test.sign);//undefined
5.function Person(name, age, sex){
var a = 0;
this.name = name;
this.age = age;
this.sex = sex;
function sss(){
a ++;
document.write(a);
}
this.say = sss;
}
var oPerson = new Person();
oPerson.say();//1
oPerson.say();//2
var oPerson1 = new Person();
oPerson1.say();//1
6. Instead, you can output 0-9 In the form of
function bb() {
var arr = [];
for(var i = 0; i < 10; i++ ) {
arr[i] = function () {
document.write(i);
}
}
return arr;
}
var arr1 = bb();
for(var i = 0; i < 10; i++ ) {
arr1[i]();
}
7.
var str = false + 1;
document.write(str);//1
var demo = false == 1;
document.write(demo);//false
if(typeof(a)&&-true + (+undefined) + "")// String type
{
document.write(' A solid ');
}
if(11 + "11" * 2 == 33)
{
document.write(' A solid ');
}
!!" " + !!"" - !!false||document.write(' You think you can print , You are a pig ');
//true + false - false
边栏推荐
- What is an app circle of friends advertisement
- Tencent music knowledge map search practice
- [deep learning series] - visual interpretation of neural network
- Sonar series: continuous scanning through Jenkins integrated sonarqube (IV)
- Section 13: simplify your code with Lombok
- Log4j2 vulnerability battle case
- Slenium tips: how to handle some dialog boxes that may appear on Web pages
- Nine built-in objects of JSP and four scopes of Servlet
- CiteSpace download installation tutorial
- Basic process of configuring utf8 in idea
猜你喜欢
![[summary] 2021unctf Campus (cry & MISC)](/img/b1/8c4fb9c6d4f1b89361c0487762cdbd.jpg)
[summary] 2021unctf Campus (cry & MISC)
Web components series (11) -- realizing the reusability of mycard
Chrome plugin installation

Cvpr2020 | the latest cvpr2020 papers are the first to see, with all download links attached!
laf. JS - open source cloud development framework (readme.md)
MySQL lock
[data recovery in North Asia] a data recovery case in which the upper virtual machine data is lost due to the hard disk failure and disconnection of raid6 disk array

Jingxi Pinpin wechat applet -signstr parameter encryption
2022 oceanbase technical essay contest officially opened | come and release your force

Flexible scale out: from file system to distributed file system
随机推荐
2022 oceanbase technical essay contest officially opened | come and release your force
Unable to connect to the server remotely locally using the Jupiter notebook
Day 29/100 local SSH password free login to remote
Popular understanding of deviation and variance in machine learning
What is API
Docker failed to remotely access 3306 after installing MySQL
Web components series (11) -- realizing the reusability of mycard
Boomfilter learning
Share several Threat Intelligence platforms
COMP9024
[golang] leetcode intermediate - the kth largest element in the array &
After 20 days' interview, I finally joined Ali (share the interview process)
8 minutes to understand the wal mechanism of tdengine
Interviewer: why does TCP shake hands three times and break up four times? Most people can't answer!
Redis common principles interview
Cloud development practice of the small program for brushing questions in the postgraduate entrance examination - page design and production (home page of the question bank, ranking page, my)
Common optimization of e-commerce server system architecture
Paddledtx v1.0 has been released, and its security and flexibility have been comprehensively improved!
Must see the summary! In depth learning era, you should read 10 articles to understand image classification!
Is it safe for Xiaobai to open a stock account online?