current position:Home>JavaScript - prototype, prototype chain
JavaScript - prototype, prototype chain
2022-04-29 15:35:48【The wind blows and the clouds fly】
Write it at the front :
Many people can't tell __proto__ and prototype , Here is an example :
prototype It's a sum of money you earn from your own work , and __proto__ It's the money your father earns from working , When you were killed by your father new When I came out , His money is your money , But if you have brothers and sisters , They can also use your father's money , however prototype It's your own money , Your brothers and sisters can't use . In a nutshell , Your father ( Constructors ) Every time you create one children ( example ), Your father's own money (prototype: Your father is also human , His money belongs to him prototype) It's like you ( example ) Of __proto__
1. Preliminary understanding of prototype
let arr = ["hello"];
console.log(arr.concat("world"));
Here's the picture ,__proto__ The attribute is Array Prototypes of objects , because arr yes Array Instantiate the object , therefore arr You can also use Array The archetypal approach
let a = {
};
let b = {
};
console.log(Object.getPrototypeOf(a) === Object.getPrototypeOf(b));//true
2. Objects without prototypes
let hq = {
name: "hq" };
console.log(hq.hasOwnProperty("name"));//true
// Full data dictionary object
let obj = Object.create(null, {
name: {
value: "hello",
},
});
console.log(obj);
3. Prototype method and object method priority
let hd = {
render() {
console.log("hd render");
},
};
hd.__proto__.render = function () {
console.log("hq");
};
hd.render();//hd render
* Use your own , No one will find it on the prototype
4. Function has multiple elders
function User() {
}
console.dir(User)
*prototype: Serve instantiated objects
function User() {
}
User.prototype.show = function () {
console.log("hello");
};
let hq = new User();
console.log(User.prototype === hd.__proto__);//true
*proto: Serve function objects
function User() {
}
User.__proto__.view = function () {
console.log("user view");
};
User.view();//user view
* Functions can be used as constructors , It can also be used as a function object
5. Prototype relationship and attribute inheritance instance
function User() {
}
console.dir(User.__proto__=== Function.prototype);//true
Code above , because User Actually by new Function Created , therefore User The prototype of the __proto__ Just === Function Of prototype
User.prototype.__proto__ === User.__proto__.__proto__; //true
Code above , Let's first analyze User.prototype Namely User The prototype of the constructor itself , But this prototype prototype It's also an object in itself , And this prototype The of the object is actually through Object Constructed . We'll see User.proto, because User It's through new Function To the , therefore its __proto__ Is equal to Function.prototype. and Function Of prototype and User Of prototype It's all through Object Created objects , So their prototype __proto__ Equal
6. Prototype of system constructor
let arr = []; //new Array
console.log(arr.__proto__ === Array.prototype);//true
let str = ""; //new String
console.log(str.__proto__ === String.prototype);//true
let bool = true; //new String
console.log(bool.__proto__ === Boolean.prototype);//true
let reg = /a/i; //new RegExp
console.log(reg.__proto__ === RegExp.prototype);//true
let obj = {
}; //new Object
console.log(obj.__proto__ === Object.prototype);//true
Take a look at it.
console.dir(Object.__proto__)
Output is as follows :
A proper function
you 're right ,Object through Function Constructed .
7. Custom object prototype settings
* Set up prototypes :setPrototypeOf
let obj = {
};
let parent = {
name: "parent"};
Object.setPrototypeOf(obj, parent);
* Get the prototype :getPrototypeOf
let obj = {
};
let parent = {
name: "parent", age: 18 };
Object.setPrototypeOf(obj, parent);
console.log(Object.getPrototypeOf(obj));
8. In the prototype constructor quote
* Through archetypal constructor You can find the constructor
function User() {
}
console.log(User.prototype.constructor === User);//true
function User(name) {
this.name = name;
}
User.prototype = {
constructor: User,
show() {
console.log(this.name)},
};
let ls = new User(" Li Si ");
ls.show();// Li Si
9. Create objects based on instances
Let's look at the following code first :
function Admin() {
}
let obj = new Admin();
console.log(obj.__proto__.constructor === Admin);//true
vernacular : Instantiate the prototype of the object __proto__ In the middle of constructor Property points to the constructor itself
Understand again :
function User(name) {
this.name = name;
this.show = function () {
console.log(this.name);
};
}
let ls = new User(" Li Si ");
function createByObj(obj, ...args) {
// find obj Prototype constructor
const constructor = Object.getPrototypeOf(obj).constructor;
return new constructor(...args);
}
let zs = createByObj(ls, " Zhang San ");
zs.show();
10. Prototype testing instanceof
- a Whether there are prototypes on the object chain A Of this constructor prototype
function A() {
}
let a = new A();
console.log(a instanceof A)//true
function A() {
}
function B() {
}
let b = new B();
A.prototype = b
let a = new A();
console.log(a instanceof B)//true
11.Object.isPrototypeOf Prototype testing
let a = {
}
let b = {
}
// b Whether the object is in a Object's prototype chain
console.log(b.isPrototypeOf(a))//false
console.log(Object.prototype.isPrototypeOf(a))//true
// hold b Object is set to a Prototypes of objects
Object.setPrototypeOf(a, b)
console.log(b.isPrototypeOf(a))//true
12.in And hasOwnProperty Detect the properties of
in: Detect whether an attribute exists in an object or the prototype chain of the object
let a = {
url: 'baidu.com' }
let b = {
name: 'baidu' }
console.log('url' in a)//true
Object.prototype.c = 'hello'
console.log('c' in a)//true
Object.setPrototypeOf(a, b)
console.log('name' in a)
hasOwnProperty: Detect the current object , Do not check whether there is an attribute on its prototype chain
let a = {
url: 'baidu.com' }
let b = {
name: 'baidu' }
Object.setPrototypeOf(a, b)
console.log(a.hasOwnProperty('name'))//false
let a = {
url: 'baidu.com' }
let b = {
name: 'baidu' }
Object.setPrototypeOf(a, b)
for (const key in a) {
// Will traverse the attributes on the prototype chain
console.log(key)
}
utilize hasOwnProperty, Only traverse its own properties
for (const key in a) {
if(a.hasOwnProperty(key))
console.log(key)
}
Prototype testing :
instanceof: An object Whether or not there is Some constructor Of prototype
isPrototypeOf: An object Whether in Another object On the prototype chain
Property detection :
hasOwnProperty: testing The current object , Do not check whether there is... On its prototype chain An attribute
in: testing An attribute Does it exist in An object perhaps The prototype chain of the object On
13. Use call or apply Borrowing from the prototype chain
let obj = {
data: [1, 3, 2, 6, 5] }
Object.setPrototypeOf(obj, {
max() {
return this.data.sort((a, b) => b - a)[0]
}
})
let zs = {
lessons: {
js: 34, php: 53, node: 66 },
get data() {
return Object.values(this.lessons)
}
}
console.log(obj.max.apply(zs))//66
let obj = {
data: [1, 3, 2, 6, 5] }
Object.setPrototypeOf(obj, {
max(data) {
return data.sort((a, b) => b - a)[0]
}
})
let zs = {
lessons: {
js: 34, php: 53, node: 66 },
}
console.log(obj.max.call(null, Object.values(zs.lessons)))//66
14.DOM Node borrowing Array Prototype method
<body>
<button message='1' class="one">1</button>
<button message='2'>1</button>
<script>
let btns = document.querySelectorAll('button')
btn = Array.prototype.filter.call(btns, item => {
return item.hasAttribute('class')
})
console.log(btn[0].innerHTML);//1
</script>
</body>
15. Reasonable constructor method declaration
function User(name) {
this.name = name;
this.show = function () {
console.log(this.name)
}
}
let ls = new User(' Li Si ')
let zs = new User(' Zhang San ')
console.log(ls);
console.log(zs);
Object oriented , Save only object properties , about show Method does not need to open up independent memory, resulting in waste
as follows , take show Method into the prototype
function User(name) {
this.name = name;
}
User.prototype.show = function () {
console.log(this.name);
}
let ls = new User(' Li Si ')
let zs = new User(' Zhang San ')
16.this It has nothing to do with the prototype
let obj = {
name: ' Zhang San ',
show() {
console.log(this.name)
}
}
Object.setPrototypeOf(obj, {
})
obj.show()// Zhang San
No matter how the prototype is changed , our this Always point to the object that calls it
let obj = {
name: ' Zhang San ',
}
let User = {
name: ' Li Si ',
show() {
console.log(this.name)
}
}
Object.setPrototypeOf(obj, User)
obj.show()//' Zhang San '
17.__proto__ Is a property accessor
* Strictly speaking __proto__ It's not an attribute , It is getter setter
let obj = {
name: " Zhang San " };
obj.__proto__ = {
show() {
console.log(this.name);
},
};
console.log(obj.__proto__);
Above , We will obj Of __proto__ Set to another object ,ok, That's all right. , But look below
let obj = {
name: " Zhang San " };
obj.__proto__ = {
show() {
console.log(this.name);
},
};
obj.__proto__ = 99// a key
console.log(obj.__proto__);
( Not the same screenshot as above !)
you 're right , Its output is the same as above , This is because it is a getter and setter , Its assignment operation is judged .
The meaning is as follows :
let obj = {
action: {
},
get proto() {
return this.action;
},
set proto(value) {
if (value instanceof Object) {
this.actioin = value;
}
},
};
obj.proto = "abc";
console.log(obj.proto);//{}
Above , Did not "abc" Set up the success , But set it as an object as follows , Then it can be set successfully
obj.proto = {
show: function () {
},
};
console.log(obj.proto);
The overlord bent his bow
let obj = Object.create(null);
obj.__proto__ = 99;
console.dir(obj.__proto__);//99
adopt Object.create Let it not inherit Object The prototype of the , Orphan it , In this way, you can set its __proto__ attribute ( This is the attribute )
copyright notice
author[The wind blows and the clouds fly],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291415481435.html
The sidebar is recommended
- JQuery realizes picture switching
- Technology sharing | test platform development - Vue router routing design for front-end development
- Return to the top - wepy applet - front end combing
- Install less / sass
- Node. JS basic tutorial
- Have you learned how to use Vue?
- The front end can't calm me down
- Introduction to JavaScript
- Vue
- Technology sharing | learning to do test platform development vuetify framework
guess what you like
Vue starts with an error and prompts NPM install core- [email protected] // oryarn add core- [email protected]
STM32 + esp8266 + air202 basic control chapter - 201 - server reverse proxy - server installation nginx (. Windows system)
STM32 + esp8266 + air202 basic control chapter - 205 - server reverse proxy - Web server configuration HTTPS access (. Windows system)
Element after the spring frame assembly is opened, the scroll bar returns to the top
Java project: nursing home management system (java + springboot + thymeleaf + HTML + JS + MySQL)
Java project: drug management system (java + springboot + HTML + layui + bootstrap + seals + MySQL)
What are the similarities and differences between jQuery and native JS?
The starting price is less than 90000 yuan, and the National University's seven seat super value SUV xinjietu x70s is officially pre sold
Fastadmin modifies the list width (limit the list width, support CSS writing), and the width limit. It is too large or useless.
Learning ajax in Vue is enough
Random recommended
- Rasa dialogue robot serial 7 lesson 122: rasa dialogue robot debugging project practical bank financial dialogue robot whole life cycle debugging practice - (III)
- CSS foundation-15-drop-down menu
- Only one message prompt pops up in the element UI at a time
- Leetcode 82. Delete duplicate elements in the sorting linked list II
- This beast was blessed with skills to test drive the DHT version of Harvard beast
- Vue Click to switch the background color randomly (small demo)
- In the era of man-machine war, how did Beijing magic cube and artificial intelligence produce chemical reaction
- About nginx + Nacos using domain name connection invalid things
- How strong is the giant wave hybrid blessing when GAC motor shadow cool makes its global debut?
- Layui framework application FAQ
- Layui style optimization
- Post request (http-c4e7.post)
- Is low code a blessing or a challenge for programmers?
- Use the pointer of the array to test the relationship between the two-dimensional elements and the column of the array in the order of "% 1-6", and then use the pointer of the array to output the data in the order of "% 1-6", and then use the pointer of t
- 6-2 pointer and the sum fraction of each column of array matrix 10 this problem requires the implementation of a function to find the sum of each column of a two-dimensional array with n (less than 10) rows and 7 columns. The columns and are stored in a o
- 7-1 find the specified element in the array
- When using uniapp for e-commerce projects, vuex is used to realize the global sharing of data to make shopping cart pages
- JQuery Basics
- `JQuery ` advanced
- Do not leave the market unless necessary! Zhongshan City issued specific requirements for campus epidemic prevention after the May Day holiday
- Software design pattern -- Chapter 3 structural pattern -- sharing element pattern
- Vue uses the online form of Excel in the front end of lucky sheet to import, display and export Excel files
- Vue uses echart to draw national maps and overlay charts
- Vue + element UI: Vue user-defined instruction monitors the scrolling event of El table to scroll the scroll bar to the bottom and load new data
- Vue + element when there is no paging at the back end, the front end completes the paging of El table independently - scrolling to the bottom to load new data
- [react] react routing concept
- Lenovo z475 disassembly and repair - plate No. kl6c
- Random array into an array, requiring that the elements cannot be repeated
- The belated Toyota bz4x, even with the blessing of e-tnga architecture, is still not worth starting
- In element plus, for example, how to change the checkbox status in the list by clicking on the header and selecting all
- Crawler reverse advanced, using ast technology to restore JavaScript obfuscated code
- Help, after changing the user name, the computer is useless and can't log in
- Drag the left column of Vue and keep the right width unchanged; The scroll bar appears
- HTML notes
- In depth analysis of headless single linked list -- dynamic diagram demonstration of C language
- Share 9 development skills related to vue3
- CSS box centered
- Used in Vue projects Sync modifier and $emit (update: XXX)
- Vue class & Style binding and computed
- Vue project uses this$ forceUpdate(); Force render page