如何访问由自己的属性遮蔽的原型链中的属性? [英] How to access properties from the prototype chain that are shadowed by own properties?

查看:120
本文介绍了如何访问由自己的属性遮蔽的原型链中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们创建一个继承自另一个匿名对象的对象:

Let's create an object which inherits from another anonymous object:

var obj = Object.create({
    func: function () { alert('Inherited method'); }
});

现在 obj 继承 func 来自该匿名对象的方法( obj 的原型链接指向该匿名对象)。

Now obj inherits the func method from that anonymous object (obj's prototype link points to that anonymous object).

obj.func(); // alerts 'Inherited method'

但是如果我们分配一个 func 属性 obj 本身,继承的 func 属性将阴影

But if we assign a func property on obj itself, the inherited func property will be shadowed:

obj.func = function () { alert('Own method'); };

obj.func(); // alerts 'Own method'

现场演示: http://jsfiddle.net/PLxHB/

现在,如果我们想要调用那个带阴影的 func 方法(提醒'继承方法'的方法),什么是好的这样做的方法?

Now, if we wanted to invoke that shadowed func method (the one that alerts 'Inherited method'), what would be a good way to do that?

我已经提出了一个解决方案 - 看到这里 - 但它有点像黑客。

I've already come up one solution - see here - but it's kind-of a hack.

推荐答案

Object.getPrototypeOf(obj).func();

将确保继承的函数被执行。

will make sure the inherited function gets executed.

在旧版浏览器中(以上为ES5),您可以使用

In older browsers (the above is ES5), you can use

obj.__proto__.func();

但不推荐使用。

< a href =http://jsfiddle.net/pimvdb/PLxHB/5/ =nofollow> http://jsfiddle.net/pimvdb/PLxHB/5/

这篇关于如何访问由自己的属性遮蔽的原型链中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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