确定原型链中方法的起源 [英] Determine origin of method in prototype chain

查看:94
本文介绍了确定原型链中方法的起源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下原型链.

Lets say that i have the following prototype-chain.

function Vehicle() {}
Vehicle.prototype.drive = function() { console.log("I'm driving"); };
Vehicle.prototype.turnOn = function() { console.log("Wrom wrom"); }; 

function Car() {}
Car.prototype = new Vehicle();
Car.prototype.honkHorn = function() { console.log("*loud sound*"); };

var car = new Car();

我正在使用for循环遍历car对象,并想确定方法源自哪个对象,如下所示:

I'm iterating over the car-object with a for-loop and want to determine which object the method origins from like so:

for (var prop in car) {
    console.log(car[prop].nameOfItsOrigin);
}

我希望得到的结果是这样的方法来源列表:

The outcome i am hoping for is a list of the methods origin like so:

Vehicle
Vehicle
Car

推荐答案

您可以通过遍历原型链来找到从其继承属性的对象:

You can find the object from which a property is inherited by traversing the prototype chain:

function origin(obj, prop) {
    for (; obj != null; obj=Object.getPrototypeOf(prop))
        if (Object.prototype.hasOwnProperty.call(obj, prop))
            return obj;
    return obj;
}
// or, recursively:
function origin(obj, prop) {
    if (obj == null || Object.prototype.hasOwnProperty.call(obj, prop))
        return obj;
    return origin(Object.getPrototypeOf(obj), prop);
}

那你就可以做

for (var p in car)
    console.log(p, origin(car, p), origin(car, p).constructor.name)

honkHorn, {…}, Car
drive, {…}, Vehicle
turnOn, {…}, Vehicle

这篇关于确定原型链中方法的起源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆