下面的例子展示了如何修改基本类型对象的 constructor 属性的值。只有 true, 1 和 “test” 的不受影响,因为创建他们的是只读的原生构造函数(native constructors)。这个例子也说明了依赖一个对象的 constructor 属性并不安全。
    代码:

    1. function Type() {};
    2. var types = [
    3. new Array,
    4. [],
    5. new Boolean,
    6. true, // remains unchanged
    7. new Error,
    8. new Function,
    9. function () {},
    10. Math,
    11. new Number,
    12. 1, // remains unchanged
    13. new Object,
    14. {},
    15. new RegExp,
    16. /(?:)/,
    17. new String,
    18. "test" // remians unchanged
    19. ]
    20. types.forEach((value)=>{
    21. console.log( (value instanceof Type) + " constructor: " + value.constructor + " \n")
    22. })
    23. for (var i = 0; i<types.length ; i++){
    24. types[i].constructor = Type ;
    25. types[i] = [types[i].constructor , types[i] instanceof Type ,types[i].toString() ];
    26. }
    27. console.log("修改之后:\n")
    28. console.log(types.join("\n"))

    打印结果:

    1. false constructor: function Array() { [native code] }
    2. false constructor: function Array() { [native code] }
    3. false constructor: function Boolean() { [native code] }
    4. false constructor: function Boolean() { [native code] }
    5. false constructor: function Error() { [native code] }
    6. false constructor: function Function() { [native code] }
    7. false constructor: function Function() { [native code] }
    8. false constructor: function Object() { [native code] }
    9. false constructor: function Number() { [native code] }
    10. false constructor: function Number() { [native code] }
    11. false constructor: function Object() { [native code] }
    12. false constructor: function Object() { [native code] }
    13. false constructor: function RegExp() { [native code] }
    14. false constructor: function RegExp() { [native code] }
    15. false constructor: function String() { [native code] }
    16. false constructor: function String() { [native code] }
    17. 修改之后:
    18. function Type() {},false,
    19. function Type() {},false,
    20. function Type() {},false,false
    21. function Boolean() { [native code] },false,true
    22. function Type() {},false,Error
    23. function Type() {},false,function anonymous(
    24. ) {
    25. }
    26. function Type() {},false,function () {}
    27. function Type() {},false,[object Math]
    28. function Type() {},false,0
    29. function Number() { [native code] },false,1
    30. function Type() {},false,[object Object]
    31. function Type() {},false,[object Object]
    32. function Type() {},false,/(?:)/
    33. function Type() {},false,/(?:)/
    34. function Type() {},false,
    35. function String() { [native code] },false,test