当前位置:网站首页>The way to understand JS: the principle of object.call and object.create() inheritance
The way to understand JS: the principle of object.call and object.create() inheritance
2022-07-26 00:18:00 【The..Fuir】
Function.prototype:call/apply/bind yes Function The archetypal approach , These three methods are all used to change the THIS Of
call:[function].call([context],params1,params2,…)
(1)[function] As Function An instance of a built-in class , Can be based on __proto__ find Function.prototype Of call Method , And put what you found call Method execution ;
(2) stay call Method execution , Will be able to [function] perform , And put this Pointing to [context], And the params1,params2… The isoparametric values are respectively passed to the function
apply:[function].apply([context],[params1,params2,…])
and call It works the same , Only the parameters passed to the function need a Array In the form of apply
bind:[function].bind([context],params1,params2,…)
(1) Grammatically and call similar , But the role and call/apply It's not the same ;
(2)call/apply It is to execute the current function immediately , And change the this Point to the , and bind It's a preprocessing idea ,
(3) be based on bind Just put the this Point to [context], hold params These parameter values are stored in advance , But at this time, the function is not executed
2. adopt Object.create(null) The object created is very pure , The properties and methods of the prototype chain will not be carried . This is very suitable for array object development , Take value from object , Improve cycle efficiency .
var obj = Object.create(null) ;
console.log(obj); // Printing can find ,obj No, __proto__ attribute
3. if necessary Use inherited properties and methods to objects , Use it obj = {} or obj = new Object() This way,Object.create The application of inheritance
var A = function () { }; A.prototype.sayName=function () { console.log('a'); } // B The instance of inherits A Properties of var B = function () { }; B.prototype = Object.create(A.prototype); var b = new B(); b.sayName(); // aFocus on : Relative to constructor inheritance Object.create Inheritance implements the A,B The prototype is perfectly separated . The two sides will not affect each other . This is a Object.create The highlight
Object.create()
effect : When there is no constructor , We want to take an existing object as a template , Then create a new instance object , We can use Object.create(); In fact, it is equivalent to copying an object .
for instance , We often encounter , Now there's an object A,A There are properties and methods , We now need a and A Have the same properties and methods , There are also some new attributes , Now we can create an object B, And then use var B=Object.create(A); here B Will inherit A Inherit all properties and methods , then B You can also create new properties and methods by yourself .
Official explanation : Method creates a new object , Using an existing object to provide a newly created object __proto__. Create instance object .
Constructor as template , You can generate instance objects . however , Sometimes I can't get the constructor , You can only get an existing object . We want to use this existing object as a template , Generate new instance objects , It can be used at this time Object.create() Method .grammar
Object.create(proto[, propertiesObject])
Parameters :
proto Prototype object of newly created object .
[, propertiesObject] Optional . If not specified as undefined, Is the enumerable property to be added to the newly created object ( That is, the attribute defined by itself , Instead of enumerating properties on its prototype chain ) The property descriptor of the object and the corresponding property name . These attributes correspond to Object.defineProperties() Second parameter of .
Return value
A new object , With the specified prototype object and properties .
examplevar person1 = { name: ' Zhang San ', age: 38, greeting: function() { console.log('Hi! I\'m ' + this.name + '.'); } }; var person2 = Object.create(person1); person2.name // Zhang San person2.greeting() // Hi! I'm Zhang San .In the above code , object person1 yes person2 The template of , The latter inherits the properties and methods of the former
grammar :
Object.create(proto[,propertiesObject])
Parametersproto
Create a prototype of the object , Represents the object to inherit
propertiesObject( Optional )
It's also an object , Used to initialize the newly created objectnotes :Object.create(null) The object created is an empty object , There is no inheritance on this object Object.prototype Properties or methods on the prototype chain
Let's take a look at the bottom
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };F.prototype attribute , Reassigned , And point to the passed parameter o;
Should be use
Sample code :// Create a Obj object var Obj ={ name:'mini', age:3, show:function () { console.log(this.name +" is " +this.age); } } //MyObj Inherit obj, prototype Point to Obj var MyObj = Object.create(Obj,{ like:{ value:"fish", // Initialize assignment writable:true, // Is it rewritable configurable:true, // Can I delete , Whether it can be modified enumerable:true // Whether it can be used for in Enumerate }, hate:{ configurable:true, get:function () { console.log(111); return "mouse" }, // get object hate Property set:function (value) { // set object hate Property console.log(value,2222); return value; } } });Can you think of it MyObj What is the output result of ? What properties will there be ?( Think about it first )
Look at the results , Is it the same as you think ?
You'll find that , The first parameter , On the prototype of the return object , Rather than direct attributes , Let's review it again Object.create The underlying principles of implementation ;
The second parameter , Is to add attributes to the returned object , And set the attribute description object , About attribute description objects
边栏推荐
- Binary tree - 530. Minimum absolute difference of binary search tree
- 计算物理期刊修改
- J9 number theory: what is Dao mode? Obstacles to the development of Dao
- 【论文笔记】—目标姿态估计—EPro-PnP—2022-CVPR
- Binary tree - 110. Balanced binary tree
- 栈的表示和实现(C语言)
- FreeRTOS personal notes - mutex
- The bull market will continue. Take your money 2021-05-08
- Revision of Journal of Computational Physics
- IP核:PLL
猜你喜欢

拼多多根据ID取商品详情 API 的使用说明

VMware ESXI7.0版本的安装与配置

bond网卡模式配置

Nest.js 用了 Express 但也没完全用

Redirection and request forwarding

CountDownLatch

Old laptop becomes server (laptop + intranet penetration)

Getaverse,走向Web3的远方桥梁

Binary tree -- 222. Number of nodes of a complete binary tree

The bull market is not over yet, and there is still 2021-05-18 in the second half
随机推荐
06_ue4进阶_使用地形工具设置大地图
[brother hero July training] day 24: linear tree
nodejs启动mqtt服务报错SchemaError: Expected `schema` to be an object or boolean问题解决
Binary tree - 110. Balanced binary tree
Appium中控件元素封装类梳理
滑动窗口_
基于SEIR模型的网络医疗众筹传播建模与仿真分析
Get JD product details original data API
Binary tree - 112. Path sum
Binary tree - 226. Flip binary tree
Prometheus operation and maintenance tool promtool (II) query function
Jd.com searches for product API instructions by keyword
Understanding of "dbdnet: a deep boosting strategy for imagedenoising"
Pinduoduo gets the usage instructions of the product details API according to the ID
CountDownLatch
服务器如何搭建虚拟主机?
Installation and configuration of VMware esxi7.0
一个List到底能存多大的数据呢?
VMware ESXI7.0版本的安装与配置
Js理解之路:什么是原型链

