从类调用方法而不实例化它 [英] call method from class without instantiate it
问题描述
我会尽力澄清 例如,如果您使用像cocos2d-x这样的框架
i will try to make it clear as i can if you look to frameworks like cocos2d-x for example
cc.Sprite.extend();
这里的Sprite是类,我们如何在不使用new
关键字
Sprite here is class how we can call method without instantiate it with new
keyword
我有一个类,例如
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 reference a method a class without instantiating it
推荐答案
基本上,您想要的是静态方法.有多种方法可以实现这一目标.我认为,使用对象文字可以为您轻松完成.
Basically what you want is a static method. There are different ways to achieve that. I think, using an object literal would the easier thing to do for you.
乱扔物体:
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();
请注意,方法init
在SuperClass
实例对象中将不可用,因为它在对象原型中不可用.
Note, the method init
won't be available in the SuperClass
instance object as 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.
ES6:
这在ES6中要好得多
class SuperClass {
static init() {
console.log("new class constructed !")
}
}
SuperClass.init();
这篇关于从类调用方法而不实例化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!