This article brings you an introduction to the usage of Object.create() in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
The object created by Object.create(null) is an empty object, and the object does not inherit the properties or methods on the Object.prototype prototype chain
For example: toString(), hasOwnProperty( ) and other methods
Parameters | Description |
---|---|
obj | Create the prototype of the object, indicating the object to be inherited |
propertiesObject (optional) | is also an object used to initialize newly created objects |
Let’s take a look at the underlying implementation
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
Let’s take a look at the specific application:
//创建一个Obj对象 var Obj ={ name:'mini', age:3, show:function () { console.log(this.name +" is " +this.age); } } //MyObj 继承obj, prototype指向Obj var MyObj = Object.create(Obj,{ like:{ value:"fish", // 初始化赋值 writable:true, // 是否是可改写的 configurable:true, // 是否能够删除,是否能够被修改 enumerable:true //是否可以用for in 进行枚举 }, hate:{ configurable:true, get:function () { console.log(111); return "mouse" }, // get对象hate属性时触发的方法 set:function (value) { // set对象hate属性时触发的方法 console.log(value,2222); return value; } } });
Application of Object.create inheritance:
var A = function () { }; A.prototype.sayName=function () { console.log('a'); } // B的实例继承了A的属性 var B = function () { }; B.prototype = Object.create(A.prototype); var b = new B(); b.sayName(); // a
Key point: Compared with the inheritance of the constructor, Object.create inheritance realizes the perfect separation of the prototypes of A and B. Both parties will not affect each other. This is the highlight of Object.create
The above is the detailed content of Introduction to the usage of Object.create() in JavaScript. For more information, please follow other related articles on the PHP Chinese website!