检查方法是静态运行还是从Javascript中的实例运行

McS*_*man 1 javascript

编写一个小方法,我希望既可以作为对象中的方法,也可以从原型中静态运行.

这是一个例子:

function Obj() {}

Obj.prototype.func = function() {

    if( this.instantiated ) { // Yes I know this is not valid code!

        // instantiated code here

    } else {

        // instantiated code here

    }

};

var myObj = new Obj();

myObj.func();

Obj.prototype.func();
Run Code Online (Sandbox Code Playgroud)

如何判断此变量是来自实例还是来自类?

Fel*_*ing 5

你可以做

if (this instanceof Obj)
Run Code Online (Sandbox Code Playgroud)

要么

if (this.constructor === Obj)
Run Code Online (Sandbox Code Playgroud)

要么

if (this !== Obj.prototype)
Run Code Online (Sandbox Code Playgroud)

虽然那更脆弱(想想var foo = Obj.prototype.func;).

您也可以在构造函数中的实例上设置某种"魔术"属性,并测试它的存在,就像您一样this.instantiated.