问题描述
在所有文章中都写道,JavaScript是一种基于原型的语言,这意味着每个对象都有一个原型(或更确切地说,原型链)。
In all the articles it is written that JavaScript is a prototype-based language, meaning that every object has a prototype (or, more precisely, prototype chain).
到目前为止,我已经尝试了以下代码片段:
So far, I've tried the following code snippet:
var F = function();
F.prototype.member1 = 1;
var object1 = new F();
console.log(object1.member1); // prints 1
如何访问 object1的原型对象
?是否存在与浏览器无关的方式(我的意思是,不依赖于 __ proto __
属性?看到链接,但也许自2010年以来有新的发展)如果我不能,你能不能分享一下背后的理由引擎盖?
How can I access the prototype object of object1
? Is there a browser-neutral way to do that (I mean, not relying on __proto__
property? Seen this link, but maybe there are new developments since 2010) If I can't, could you share please the rationale behind the hood?
推荐答案
var f = function();
var instance = new f();
如果您知道实例的名称
类函数,你可以简单地访问原型:
If you know name of instance
class function, you can simply access prototype as:
var prototype = f.prototype;
prototype.someMember = someValue;
如果您不这样做:
1)
var prototype = Object.getPrototypeOf(instance);
prototype.someMember = someValue;
2)或
var prototype = instance.__proto__;
prototype.someMember = someValue;
3)或
var prototype = instance.constructor.prototype; // works only if constructor is properly assigned and not modified
prototype.someMember = someValue;
为了兼容性,您可以在代码中放入以下代码段(并始终使用 Object.getPrototypeOf(instance)
返回原型):
For compatibility you can place into your code the following snippet (and use always Object.getPrototypeOf(instance)
to return prototype):
if(!Object.getPrototypeOf) {
if(({}).__proto__ === Object.prototype && ([]).__proto__ === Array.prototype) {
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__;
};
} else {
Object.getPrototypeOf = function getPrototypeOf(object) {
// May break if the constructor has been changed or removed
return object.constructor ? object.constructor.prototype : void 0;
};
}
}
更新:
根据ECMA-262第6版(2015年6月) __ proto __
属性被标准化为Web的附加功能浏览器。所有最新版本的顶级浏览器现在都支持它。了解更多关于 __ proto __
:
According to ECMA-262 6th Edition (June 2015) __proto__
property is standardized as additional feature for Web browsers. All latest editions of top browsers supports it now. Read more about __proto__
:
-
MDN:
EDMA-262第6版(2015年6月):
EDMA-262 6th Edition (June 2015): B.2.2.1 Object.prototype.__proto__
这篇关于如何在javascript中访问对象原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!