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

Define property in the Object prototype and get the object's type

本文关键字:获取 取对象 类型 属性 Object 原型 定义      更新时间:2023-09-26

我在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" ?

以上代码的演示。

PS:不好意思,这个标题太糟糕了。如果有人知道如何做得更好,自我解释就好了。

您要查找的是instanceof操作符:

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

对于不将this值强制转换为对象,您可以使用严格模式:

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"