I need to understand how the Array
object gets a reference to Object
.
For example, when I create var arr = [];
it has Array.prototype
---> Object.prototype
---> null
.
I want to achieve above for the example below:
Suppose I have a function xyz()
, where xyz.prototype.somefunction = function() { }
.
I have another function abc()
, where abc.prototype.anotherfunction = function() { }
.
When I create an object of abc()
— as in var obj = new abc()
— I want it to have a prototype chain like obj
---> abc.prototype
---> xyz.prototype
---> object.prototype
---> null
.
Please suggest the best way to do this.
function xyz() {}
function abc() {}
var p = new xyz();
abc.prototype = p;
var o = new abc();
o.__proto__ === p // true
o.__proto__.__proto__ === xyz.prototype // true
o.__proto__.__proto__.__proto__ === Object.prototype // true
o.__proto__.__proto__.__proto__.__proto__ === null // true
Or:
function xyz() {}
function abc() {}
var p = Object.create(xyz.prototype);
abc.prototype = p;
var o = new abc();
o.__proto__ === p // true
o.__proto__.__proto__ === xyz.prototype // true
o.__proto__.__proto__.__proto__ === Object.prototype // true
o.__proto__.__proto__.__proto__.__proto__ === null // true
Or:
class xyz {}
class abc extends xyz {}
var o = new abc();
o.__proto__.__proto__ === xyz.prototype // true
o.__proto__.__proto__.__proto__ === Object.prototype // true
o.__proto__.__proto__.__proto__.__proto__ === null // true
Or:
function xyz () {}
const abc = {
__proto__: Object.create(xyz.prototype)
}
abc.__proto__.__proto__ === xyz.prototype // true
abc.__proto__.__proto__.__proto__ === Object.prototype // true
abc.__proto__.__proto__.__proto__.__proto__ === null // true
Or:
function xyz () {}
function abc() {}
Object.setPrototypeOf(abc.prototype, xyz.prototype);
var o = new abc();
o.__proto__.__proto__ === xyz.prototype // true
o.__proto__.__proto__.__proto__ === Object.prototype // true
o.__proto__.__proto__.__proto__.__proto__ === null // true
You can do prototypical inheritance:
abc.prototype = new xyz();
now, when you create a new object, it will follow the chain you desire.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.