没有"Function.method"在JavaScript中? [英] No "Function.method" in JavaScript?

查看:35
本文介绍了没有"Function.method"在JavaScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读道格拉斯·克罗克福德(Douglas Crockford)的书,他使用的是

I am reading the book by Douglas Crockford, and he uses the construct of

Function.method('inherits', function(Parent){
   this.prototype=new Parent();
   return this;
});

如果我们不理会它的含义,我简直无法绕开语法.我尝试在chrome中运行它,并获得

If we leave alone the meaning of it, I simply can't get around the syntax. I try to run it in chrome, and get

Uncaught TypeError: undefined is not a function test3.html:18
(anonymous function)

如果我尝试( jsfiddle )也会发生

as also happens with if I try (jsfiddle)

Function.method("test", function () { return "TEST"; });

似乎有一个帖子,其中说这行有效,但我无法使其正常工作.为什么会这样?

There seems to be a post which says this line is working, but I can't make it work. Why can it be?

推荐答案

该行在

The reason that line is working in the post you refer to is because Function.prototype has been extended with the method:

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};

如果您运行上述代码,然后再运行您拥有的代码,一切都会正常-或您可以将 .method 更改为 .prototype [name_here] = 一切都会一样.

If you run the above code and only then run the code you have, everything will work - or you can just change .method to .prototype[name_here] = and everything will work the same.

如果您打算在当今时代扩展原型,最好使用

If you are going to extend prototypes in this day and age it is better to use Object.defineProperty to ensure that the method is not enumerable.

这篇关于没有"Function.method"在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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