用定制原型在javascript中创建函数 [英] create function in javascript with custom prototype

查看:123
本文介绍了用定制原型在javascript中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建了一个这样的函数,

  var functionName = function(arg1){//这里的代码逻辑; } 

同时,我需要这个函数作为一个对象。它不会真的保存任何东西,但数据将从另一个对象访问。

  var myObj = new Object(); 
myObj.x = 3;
myObj.y = 4;

所以当我去时, functionName.x 它应该返回 myObj.x myObj 对象正在其他地方维护,我没有任何控制权。



这就是我目前实现它,

  functionName .__ proto__ = myObj; 

工作正常。但是 __ proto __ 已被弃用,我想查看是否有其他安全的方法。我想重写 Function.prototype 但它不起作用。 p>我在这里遇到同样的问题。不幸的是,在EcmaScript 5.1下没有好的解决方案。



在语言规范 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf 它在13.2 创建函数对象表示新创建的函数对象的[[Prototype]]内部属性始终是标准的内置函数原型对象。



如13.3使用Function构造函数也是没有帮助的,因为由 new函数(...)构造的函数也使用13.2中详述的方法。 (这反映了功能原型属性既不可写也不可配置的事实。



所以为了实现你想要的,你需要一种方法来改变已经存在的对象的原型。幸运的是,即将到来的Ecmascript 6标准似乎标准化了 Object.prototype。 __proto __ 根据近期草案中的附录B.2.2 http://wiki.ecmascript.org/lib/exe/fetch.php?id=harmony%3Aspecification_drafts&cache=cache& ; media = harmony:working_draft_ecma-262_edition_6_05-14-13-nomarkup.pdf


So I created a function like this,

var functionName = function(arg1) { //code logic here; }

At the same time, I need this function to work as an object. It will not really save anything, but the data will be accessed from another object.

var myObj = new Object();
myObj.x = 3;
myObj.y = 4;

So when I go, functionName.x it should return myObj.x. The myObj object is being maintained someplace else and I don't have any control of it.

This is how I currently implemented it,

functionName.__proto__ = myObj;

It works fine. But __proto__ is deprecated already and I would want to see if there is any other safe way of doing it. I thought of overriding Function.prototype but it doesn't work.

解决方案

I am having the same problem here. Unfortunately, there is no good solution under EcmaScript 5.1.

In the language specification http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf it says in 13.2 "Creating Function Objects" that the [[Prototype]] internal property of a newly created function object is always the standard built-in Function prototype object.

As detailed in 13.3 of the same specification, using the Function constructor is also of no help as a function constructed by new Function(…) also uses the method detailed in 13.2. (This is reflected by the fact that the prototype property of Function is neither writable nor configurable.

So to achieve what you want, you need a method to change the prototype of already existing objects. Fortunately, the upcoming Ecmascript 6 standard seems to standardises Object.prototype.__proto__ as per annex B.2.2 in the recent draft http://wiki.ecmascript.org/lib/exe/fetch.php?id=harmony%3Aspecification_drafts&cache=cache&media=harmony:working_draft_ecma-262_edition_6_05-14-13-nomarkup.pdf.

这篇关于用定制原型在javascript中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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