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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...