【问题标题】:Defining global method for all classes为所有类定义全局方法
【发布时间】:2014-09-04 13:57:32
【问题描述】:

有没有办法为所有类定义全局方法?

用代码更容易描述...

Class.myMethod(){}

var Foo = function(){}
var Bar = function(){}

Foo.myMethod();
Bar.myMethod();

我知道,这很奇怪,但我需要它。

如果可能的话,如何在方法代码中获取类变量:

Class.myMethod(){
    var anything; //anything should contains current class.
}

var Foo = function(){}
var Bar = function(){}

Foo.myMethod(); // anything should be Foo
Bar.myMethod(); // anything should be Bar

【问题讨论】:

  • Function.prototype.methodName = function(){ //你的函数 }

标签: javascript class methods global


【解决方案1】:

Javascript 中没有“类”。但是,FooBar 是构造函数,即它们是函数,并且继承自 Function class.prototype object。所以你可以做

Function.prototype.myMethod = function(){
    var anything = this; // refers to the current constructor function
    console.log(anything.name); // for example
}

function Foo(){}
function Bar(){}

Foo.myMethod(); // "Foo"
Bar.myMethod(); // "Bar"

【讨论】:

  • 完美。我尝试使用 Function.method,现在可以使用您的答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-12
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多