微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Object.defineProperty或.prototype?

我已经看到了两种在 javascript中实现非本机功能的不同技术,
首先是:
if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype,'startsWith',{
        enumerable: false,configurable: false,writable: false,value: function(searchString,position) {
            position = position || 0;
            return this.lastIndexOf(searchString,position) === position;
        }
    });
}

第二是:

String.prototype.startsWith = function(searchString,position) {
    position = position || 0;
    return this.lastIndexOf(searchString,position) === position;
}

我知道第二个用于将任何方法附加到特定标准内置对象的原型链,但第一种技术对我来说是新的.
任何人都可以解释它们之间的区别,为什么使用它们以及为什么不使用它们以及它们的意义是什么.

解决方法

在两种情况下,您在String.prototype中添加一个属性“startsWith”.

在这种情况下,第一个与第二个不同:

您可以将该属性配置为可枚举,可写和可配置.

Writable – true表示您可以通过分配任何值来更改其值.如果为false – 您无法更改该值

Object.defineProperty(String.prototype,// Set to False
        value: function(searchString,position) === position;
        }
    });

var test = new String('Test');

test.startsWith = 'New Value';
console.log(test.startsWith); // It still have the prevIoUs value in non strict mode

Enumerable – true表示将在for循环中看到它.

Object.defineProperty(String.prototype,{
        enumerable: true,// Set to True
        configurable: false,position) === position;
        }
    });

var test = new String('Test');

for(var key in test){
   console.log(key)  ;
}

Configurable – 当且仅当可以更改此属性描述符的类型并且可以从相应对象中删除属性时才返回true.

Object.defineProperty(String.prototype,{
            enumerable: false,// Set to False
            writable: false,position) {
                position = position || 0;
                return this.lastIndexOf(searchString,position) === position;
            }
        });

    
    delete String.prototype.startsWith; // It will not delete the property
    console.log(String.prototype.startsWith);

并且给你一个建议,不要改变构建类型的原型.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐