简体   繁体   English

javascript原型继承如何用于Array函数

[英]How javascript prototypical inheritance works for the Array, function

I need to understand how the Array object gets a reference to Object . 我需要了解Array对象如何获取对Object的引用。

For example, when I create var arr = []; 例如,当我创建var arr = []; it has Array.prototype ---> Object.prototype ---> null . 它具有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() { } . 假设我有一个函数xyz() ,其中xyz.prototype.somefunction = function() { }

I have another function abc() , where abc.prototype.anotherfunction = function() { } . 我还有另一个函数abc() ,其中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 . 当我创建abc()的对象时abc()var obj = new abc() ,我希望它具有像obj ---> abc.prototype ---> xyz.prototype ---> object.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. 现在,当您创建一个新对象时,它将遵循您想要的链。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM