[英]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]();
}
};
当然, this
在Shape.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]();
}
我认为您正在寻找的是继承检测。 这可以通过检查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);
编辑
也许您想寻找一个由字符串定义的原型? 在这种情况下,请执行以下操作:
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.