JS-prototype
阿新 • • 發佈:2018-05-30
訪問器 ati his 返回 ref reat class ocs document
prototype
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
Object.prototype 屬性表示 Object 的原型對象。
prototype.__proto__
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Object.prototype 的 __proto__ 屬性是一個訪問器屬性(一個getter函數和一個setter函數), 暴露了通過它訪問的對象的內部[[Prototype]] (一個對象或 null)。
prototype.constructor
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
返回創建實例對象的 Object 構造函數的引用。註意,此屬性的值是對函數本身的引用,而不是一個包含函數名稱的字符串。對原始類型來說,如1,true和"test",該值只可讀。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> // Person var Person = function(name) { this.name = name; this.canTalk = true; }; Person.prototype.greet = function() { if (this.canTalk) { console.log(‘Hi, I am ‘ + this.name); } }; // Employee var Employee = function(name, title) { Person.call(this, name); this.title = title; }; Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; Employee.prototype.greet = function() { if (this.canTalk) { console.log(‘Hi, I am ‘ + this.name + ‘, the ‘ + this.title); } }; // instantiation var joe = new Person(‘Joe‘); var bob = new Employee(‘Bob‘, ‘Builder‘); // call function joe.greet(); bob.greet(); // 直接打印 console.log(Person, Employee, joe , bob) // prototype:當前對象的原型對象 console.log(Person.prototype, Employee.prototype, joe.prototype, bob.prototype) // constructor:返回當前對象構造函數的引用 console.log(Person.constructor, Employee.constructor, joe.constructor , bob.constructor) // __proto__:返回當前對象構造函數的原型 console.log(Person.__proto__, Employee.__proto__, joe.__proto__, bob.__proto__) console.log(Person.constructor.prototype, Employee.constructor.prototype, joe.constructor.prototype, bob.constructor.prototype) </script> <script> </script> </body> </html>
JS-prototype