Minor drawback with Crockford Prototypical Inheritance

爷,独闯天下 提交于 2019-11-30 19:19:04

The issue is that it's referring to the name of the constructor function. This quickly becomes a discussion about function expressions and statements and the name property. Turns out is is completely impossible to create a new named function at runtime without using eval. Names can only be specified using a function statement function fnName(){} and it's not possible to construct that chunk of code dynamically aside from evaling it. var fnExpression = function(){} results in an anonymous function assigned to a variable. The name property of functions is immutable so it's a done deal. Using Function("arg1", "arg2", "return 'fn body';") also only can produce an anonymous function despite being similar to eval.

It's basically just an oversight in the JS spec (Brendan Eich stated he regrets defining the display name the way he did 10 or so years ago) and a solution is being discussed for ES6. This would introduce more semantics for deriving a function's display name for debug tools or perhaps an explicit way to set and adjust it.

For now you have one route: eval, or some other form of late execution of configurable code. (eval by any other name...)

function displayName(name, o){
  var F = eval("1&&function "+name+"(){}");
  F.prototype = o; 
  return new F;
}

The function statement alone won't return from eval, but doing 1 && fnStatement coerces the thing into an expression which is returnable.

(Harmony Proxies also allow setting up functions that report names which you can configure without eval but that's not usable except in Node.js and Firefox currently).

I'll make a note here that all those "evil" functions that have been shat upon by Crockford and many others ALL have their place. eval, with, extending natives all enable specific techniques which are otherwise completely impossible and it's not wrong to use them when the occasion is right. It's just likely that most people aren't qualified to make the judgement of when that time is right. In my opinion using eval harmlessly to make up for poor language semantics and tools while waiting for a solution is perfectly acceptable and won't cause you any harm as long as you're not funneling arbitrary code into that eval statement.

If I log the object I can see: Object { foo="bar", baz=function()}, so I don't understand your problem...

Anyway, can use Object.create() instead of Crockford's function:

var P = {
         foo:'bar',
         baz: function(){ alert("bang"); }
         }

var C = Object.create (P);

console.log (C):

Object { foo="bar", baz=function()}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!