javascript - Object.defineProperty 还是 .prototype?

标签 javascript string object prototype defineproperty

我见过两种在 javascript 中实现非 native 功能的不同技术, 首先是:

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

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

最佳答案

在两种情况下,您要在 String.prototype 中添加新属性“startsWith”。

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

您可以将属性配置为可枚举可写可配置

Writable - true 表示您可以通过分配任何值来更改其值。如果为 false - 您不能更改该值

Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false, // Set to False
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(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 in 循环中看到。

Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: true, // Set to True
        configurable: false,
        writable: false, 
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });

var test = new String('Test');

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

Configurable - true 当且仅当可以更改此属性描述符的类型并且可以从相应对象中删除该属性时。

Object.defineProperty(String.prototype, 'startsWith', {
            enumerable: false,
            configurable: false, // Set to False
            writable: false, 
            value: function(searchString, 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);

还有一个建议,不要更改内置类型的原型(prototype)

关于javascript - Object.defineProperty 还是 .prototype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961414/

相关文章:

ios - 如何映射一个我不知道参数个数的json

javascript - 设置间隔函数不作为方法

javascript - 有没有办法扩展 ThreeJS 对象?

javascript - 从外部 HTML 添加和过滤 div

JavaScript:如何从 json 字符串中获取逗号分隔的字符串?

javascript - 选择两个词之间的文本

javascript - 从对象中切片属性并进行计数

Javascript 计数器 - 更改 InnerHtml

java - 如何在java中分离字符串以满足以下要求?

java - 删除Java字符串中的破折号并将破折号后的字符大写