在Object原型中定义属性并获取对象的类型

时间:2014-07-02 14:28:57

标签: javascript

我在Object原型上创建了一个属性,该属性是一个具有某些功能的对象:

Object.defineProperty(Object.prototype, "json", 
{
    value: function()
    {
        return {
            _value: this,
            parse: function()
            {
            }
        };
    },
    enumerable: false
});

我希望能够在任何对象上调用它,例如:

"simple string".json().parse()
// or
var a = {b:1};
a.json().parse()

parse()内部,我有this._value作为对象本身。如果是字符串,则值为:

String {0: "s", 1: "i", 2: "m", 3: "p", 4: "l", 5: "e", 6: " ", 7: "s", 8: "t", 9: "r", 10: "i", 11: "n", 12: "g", length: 13}

如果我使用typeof(this._value),则会返回"object"。在对象的情况下:

Object {b: 1}

我的问题是如何识别对象原来是一个字符串,因为它是一个对象而typeof(正确)返回给我"object"

Demo of above codes

PS:对不起的标题感到抱歉。如果有人知道如何让它更好自我解释会很好。

2 个答案:

答案 0 :(得分:2)

您正在寻找的是instanceof运营商:

("simple string".json()._value) instanceof String  ===  true

答案 1 :(得分:1)

如果没有获得投放到对象的this值,您可以使用strict mode

Object.defineProperty(Object.prototype, "json", {
    value: function() {
        "use strict";
        return {
            _value: this,
            parse: function() {
            }
        };
    }
});
typeof "simple string".json()._value // "string"
typeof new String("simple string").json()._value // "object"
相关问题