当前位置:网站首页>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
边栏推荐
- Patrol script
- Day 29/100 local SSH password free login to remote
- SaaS privatization deployment scheme
- Desktop network error display red ×, Component failed to start
- 2022 oceanbase technical essay contest officially opened | come and release your force
- Attention to government and enterprise users! The worm prometei is spreading horizontally against the local area network
- couldn‘t be accessed by user ‘_ apt‘
- [summary] 2021unctf Campus (cry & MISC)
- Analysis and cleaning of kdevtmpfsi virus content
- Slenium tips: how to handle some dialog boxes that may appear on Web pages
猜你喜欢
Install JDK, MySQL and nexus under Linux (tar package installation)
[deep learning series] - visual interpretation of neural network
Log4j2 vulnerability detection tool list
Introduction to the basics of kotlin language: lambda expression
MySQL lock
Understand the offline mixing technology in the industry
2022 oceanbase technical essay contest officially opened | come and release your force
Docker failed to remotely access 3306 after installing MySQL
Compile 6relayd using the cross compiler
laf. JS - open source cloud development framework (readme.md)
随机推荐
[summary] 2021unctf Campus (cry & MISC)
Day 28/100 CI CD basic introductory concepts
[golang] leetcode intermediate - the kth largest element in the array &
Solution to big noise of OBS screen recording software
Boomfilter learning
1.1-mq visual client preliminary practice
Why doesn't anyone read your hard-working blog? Do you really understand the skills of framing, typesetting and drawing?
Illustrated with pictures and texts, 700 pages of machine learning notes are popular! Worth learning
Recommend a free screen recording software
Attention to government and enterprise users! The worm prometei is spreading horizontally against the local area network
Share several Threat Intelligence platforms
Global netizens Yuanxiao created a picture of appreciating the moon together to experience the creativity of Baidu Wenxin big model aigc
Leetcode daily [2022 - 02 - 18]
Is it safe for Xiaobai to open a stock account online?
Decryption of APP parameters of a cross-border export e-commerce - dunhuang.com
Barrier of cursor application scenario
How to close gracefully after using jedis
Get the root directory of the package at compile time from buildreoot
Mysqldumpslow out slow statements in the database
Analysis and cleaning of kdevtmpfsi virus content