1、任何new出来的实例的prototype 都是 undefined, 但是 new Function('p', 'return 99') 除外。
// console.log(Number.prototype); // Number { 0 } // console.log(Boolean.prototype); // Boolean { false } // console.log(String.prototype); // String { "" } // console.log(Object.prototype); // Object { … } // console.log(Function.prototype); // function () // console.log(Array.prototype); // Array [] // console.log(RegExp.prototype); // RegExp.prototype { flags: "", source: "(?:)", … } // console.log(Error.prototype); // Error.prototype { stack: "", … } // console.log(Date.prototype); // Date.prototype { … } // console.log(Math.prototype); // undefined // console.log(JSON.prototype); // undefined function Func() {} var f = new Func(); console.log(f.prototype); //undefined console.log(Func.prototype); //Object { … } console.log(f.__proto__ === Func.prototype); // true 临时添加 console.log(Func.prototype.__proto__ === Object.prototype); //true 临时添加 var object = new Object(); console.log(object.prototype); // undefined console.log(object.__proto__ === Object.prototype); //true var obj = { name: "" }; console.log(obj.prototype); // undefined console.log(obj.__proto__ === Object.prototype); //true var n = new Number(1); console.log(n.prototype); // undefined console.log(n.__proto__ === Number.prototype); //true var s = new String("string"); console.log(s.prototype); // undefined console.log(s.__proto__ === String.prototype); //true var arr = new Array([]); console.log(arr.prototype); // undefined console.log(arr.__proto__ === Array.prototype); //true class AClass {} var c = new AClass(); console.log(c.prototype); // undefined var fn = new Function("p", "console.log(p)"); console.log(fn.prototype); //Object { … } console.log(fn.prototype.__proto__.prototype); // undefined console.log(fn.__proto__ === Function.prototype); //true *** constructor: function anonymous(p) console.log(fn.prototype.__proto__ === Object.prototype); //true 临时添加View Code
2、prototype都是可读可写的(不报错)。 对Function等系统内置对象的prototype重新整体赋值无效。而我们自定义的函数,如 function myfn() {} 是有效的。
var prototypeObject = { test () { console.log(999); } } console.log(Object.prototype); Object.prototype = prototypeObject; var obj = new Object(); // obj.test(); //报错 function myFunc() { } myFunc.prototype = prototypeObject; console.log(myFunc); var fn = new myFunc(); fn.test(); // 999View Code