<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script type="text/javascript" src="../jquery.js"></script> <script> var Book = function (id, name, price) { this.id = id; this.name = name; this.price = price; } var Book2 = function (id, name, price) { this.id = id; this.name = name; this.price = price; } // 在原型的基礎上 Book.prototype.display = function () { console.log(this.name); } // 直接替換原型對象 Book2.prototype = { display: function () { console.log(this.name); } } var _Book = new Book(1, 'javascript', 12); var _Book2 = new Book2(1, 'javascript', 12); console.log(_Book); console.log(_Book2); var Test = function () { }; var _Test = new Test(); console.log(_Test); // 若是在對象的原型上添加屬性和方法, 那麼他的constructor屬性會指向到當前對象, console.log(_Book.constructor == Book); // true console.log(_Book.constructor == Object); // false; // 若是在直接替換原型對象,那麼他的constructor屬性會指向最原始的對象. console.log(_Book2.constructor == Object); // true; console.log(_Test.constructor == Test); // true; // 測試某個屬性是不是自擁有的 console.log("constructor" in _Test); // true; console.log("constructor" in _Book2); // true; console.log(_Test.hasOwnProperty('constructor')); // false 不是自擁有的屬性,這個是繼承過來的. console.log(_Book.hasOwnProperty('constructor')); // false /* 知識點總結: _Book: constructor:(id, name, price) display:() __proto__:Object _Book2: display: () __proto__: Object 1 在原型上追加方法時, 對象的構造函數是存在的,若是是替換原型對象,那麼就會無構造函數, 2 若是在原型上追加方法,那麼他的構造函數是指向本身的,經過_Book,_Test的測試看到, 若是直接替換原型對象,那麼他的構造函數是指向object, */ </script> </head> <body> </body> </html>