如何在不实例化的情况下从类调用方法? [英] How can I call a method from a class without instantiating it?

查看:75
本文介绍了如何在不实例化的情况下从类调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你看看像 cocos2d-x 这样的框架,例如:

If you look at a framework like cocos2d-x, for example:

cc.Sprite.extend();

这里的 Sprite 是一个类;如何在不使用 new 关键字实例化的情况下调用其方法之一?

Sprite here is a class; how can I call one of its methods without instantiating it with the new keyword?

例如,如果我有这个类:

For example, if I have this class:

var superClass = function(){
    
    this.init = function(){
        console.log("new class constructed !")
    };

};

要调用init,我必须这样做:

To call init, I must do this:

obj = new superClass();
obj.init();

但是如何在不需要实例化类的情况下调用函数?

But how can I call the function without needing to instantiate the class?

推荐答案

ES6 及更新版本:

使用static 关键字.大多数现代浏览器都支持它.

class SuperClass {
   static init() {
     console.log("new class constructed !")
   }
}

SuperClass.init();

旧版浏览器:

有不同的方法可以实现这一目标.一种选择是使用对象字面量.

Older browsers:

There are different ways to achieve that. One option is to use an object literal.

对象字面量:

var superClass = {
    init: function(){
        console.log("new class constructed !")
    }
};

superClass.init();

https://jsfiddle.net/ckgmb9fk/

但是,您仍然可以使用函数构造函数定义对象,然后向类"添加静态方法.例如,您可以这样做:

However, you can still define an object using a function constructor and then add a static method to the "class". For example, you can do this:

var SuperClass = function(){};

SuperClass.prototype.methodA = function() {
    console.log("methodA");
};

SuperClass.init = function() {
    console.log("Init function");
}

SuperClass.init();

var sc = new SuperClass();
sc.methodA();

请注意,方法 initSuperClass 实例对象中将不可用,因为它不在对象原型中.

Note that the method init won't be available in the SuperClass instance object because it is not in the object prototype.

https://jsfiddle.net/mLxoh1qj/

扩展原型:

var SuperClass = function(){};

  SuperClass.prototype.init = function() {
      console.log("Init");
  };

SuperClass.prototype.init();

var sc = new SuperClass();
sc.init();

https://jsfiddle.net/0ayct1ry/

如果您想从 SuperClass 原型和对象实例访问函数 init,此解决方案很有用.

This solution is useful if you want to access the function init both from the SuperClass prototype and from an object instance.

这篇关于如何在不实例化的情况下从类调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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