繁体   English   中英

JavaScript字符串是原型函数吗?

[英]Javascript string is a prototype function?

我在javascript中创建了一个Shape类供画布使用,以消磨时间。 我想知道我是否可以做下面的事情,

var Shape = function (shape) {

     // pseudo code
     if (shape is a prototype function of Shape) {
         shape();
     }
}

Shape.prototype.quad = function () {

}

因此,对于上述内容,唯一有效的字符串将是quad因为这是定义的唯一原型函数。

这可能吗?

给定shape是一个字符串,只需使用in即可查看Shape.prototype是否存在

var Shape = function (shape) {
     if (shape in Shape.prototype) {
         Shape.prototype[shape]();
     }
};

当然, thisShape.prototype.quad并没有为您提供有用的this值,但我无法告诉您在那里想要什么。


如果您打算将其用作构造函数,则可以使用this

var Shape = function (shape) {
     if (shape in this) {
         this[shape]();
     }
};

如果您还想确定它是一个函数,请使用typeof

 if ((shape in this) && typeof this[shape] === "function") {
     this[shape]();
 }

jsFiddle演示

我认为您正在寻找的是继承检测。 这可以通过检查instanceof来完成。 这是一个例子:

var Shape = function (shape) {
 if( shape instanceof Shape ){
  alert("shape instance found");   
 }
};

var Quad = function(){};
Quad.prototype = new Shape();

var q = new Quad();
var s = new Shape(q);

编辑

jsFiddle演示

也许您想寻找一个由字符串定义的原型? 在这种情况下,请执行以下操作:

var Shape = function (shape) {
 if( typeof this[shape] == "function" ){
    alert("shape is a prototype function");   
 }
};
Shape.prototype.quad = function(){};

var c = new Shape("circle");
var q = new Shape("quad");

假设Shape是一个构造函数,请尝试使用此方法,它使用非标准但通常可用的原型属性。

var Shape = function (shape) {
    for (var functionName in this) {
        if (this.__proto__.hasOwnProperty(functionName)) {     
            if (this[functionName]  ===  shape) {
                shape.call(this);
            }
        }            
    }
}

Shape.prototype.quad = function () { console.log("quad")}
new Shape(Shape.prototype.quad)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM