16

我已经看到了两种在 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;
}

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

4

1 回答 1

30

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

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

您可以将属性配置为enumerable和。writableconfigurable

可写-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

可枚举-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)  ;
}

可配置-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);

给您的一个建议是,不要更改内置类型的原型

于 2016-08-15T19:14:56.313 回答