[英]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.