下面的例子展示了如何修改基本类型对象的 constructor 属性的值。只有 true, 1 和 “test” 的不受影响,因为创建他们的是只读的原生构造函数(native constructors)。这个例子也说明了依赖一个对象的 constructor 属性并不安全。
代码:
function Type() {};
var types = [
new Array,
[],
new Boolean,
true, // remains unchanged
new Error,
new Function,
function () {},
Math,
new Number,
1, // remains unchanged
new Object,
{},
new RegExp,
/(?:)/,
new String,
"test" // remians unchanged
]
types.forEach((value)=>{
console.log( (value instanceof Type) + " constructor: " + value.constructor + " \n")
})
for (var i = 0; i<types.length ; i++){
types[i].constructor = Type ;
types[i] = [types[i].constructor , types[i] instanceof Type ,types[i].toString() ];
}
console.log("修改之后:\n")
console.log(types.join("\n"))
打印结果:
false constructor: function Array() { [native code] }
false constructor: function Array() { [native code] }
false constructor: function Boolean() { [native code] }
false constructor: function Boolean() { [native code] }
false constructor: function Error() { [native code] }
false constructor: function Function() { [native code] }
false constructor: function Function() { [native code] }
false constructor: function Object() { [native code] }
false constructor: function Number() { [native code] }
false constructor: function Number() { [native code] }
false constructor: function Object() { [native code] }
false constructor: function Object() { [native code] }
false constructor: function RegExp() { [native code] }
false constructor: function RegExp() { [native code] }
false constructor: function String() { [native code] }
false constructor: function String() { [native code] }
修改之后:
function Type() {},false,
function Type() {},false,
function Type() {},false,false
function Boolean() { [native code] },false,true
function Type() {},false,Error
function Type() {},false,function anonymous(
) {
}
function Type() {},false,function () {}
function Type() {},false,[object Math]
function Type() {},false,0
function Number() { [native code] },false,1
function Type() {},false,[object Object]
function Type() {},false,[object Object]
function Type() {},false,/(?:)/
function Type() {},false,/(?:)/
function Type() {},false,
function String() { [native code] },false,test