简体   繁体   中英

Javascript string is a prototype function?

I am creating a little Shape class in javascript for canvas to kill some time. I was wondering if I could do something like below,

var Shape = function (shape) {

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

Shape.prototype.quad = function () {

}

So for the above the only valid string would be quad as that is the only prototypal function defined.

Is this possible?

Given that shape is a string, just use in to see if it exists on Shape.prototype

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

This of course doesn't give you a useful this value in Shape.prototype.quad , but I can't tell what you want there.


If you meant to do this as the constructor function, then you'd use this instead.

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

If you want also to make certain that it's a function, then use typeof .

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

jsFiddle Demo

I think what you are looking for is inheritance detection. This can be done by checking instanceof . Here is an example:

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);

edit

jsFiddle Demo

Perhaps you would like to look for a prototype defined by a string? In that case, do this:

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");

Try this assuming Shape is a constructor, it uses the non-standard but commonly available proto property.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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