1.实例对象自身的属性(第一层)
- function Person(name) {
- this.name = name
- this.listenMusic = function () {
- console.log('听音乐')
- }
- }
- const person = new Person('clz')
- console.log(person)
- console.log('实例对象本身是否有listenMusic方法', person.hasOwnProperty('listenMusic'))
- person.listenMusic()
2.实例对象的原型对象上的属性(第二层)
- function Person(name) {
- this.name = name
- }
- Person.prototype.listenMusic = function () {
- console.log('听音乐')
- }
-
- const person = new Person('clz')
- console.log(person)
- console.log('实例对象本身是否有listenMusic方法', person.hasOwnProperty('listenMusic'))
- person.listenMusic()
3.原型对象的原型对象上的属性(第三层)
- function Person(name) {
- this.name = name
- }
- Person.prototype.__proto__.listenMusic = function () {
- console.log('听音乐')
- }
-
- const person = new Person('clz')
- console.log(person)
- person.listenMusic()
4.通过__proto__形成的链条,即原型链:
person => Person.prototype => Object.prototype => null
5.图示:
测试代码:
- //数组
- let arr = [1, 2, 3];
- let str = arr.toString();
- console.log(str); //1,2,3
- console.log(arr.__proto__); //Array的原型对象
- console.log(Object.prototype); //Object的原型对象
- console.log(arr.__proto__ == Array.prototype); //true
- console.log(Array.prototype.__proto__ == Object.prototype); //true
- console.log(Array.prototype == Object.__proto__); //false
- //函数
- function User() {}
- let u1 = new User();
- let u2 = new User();
- console.log(User.prototype.constructor); //User构造函数
- console.log(u1.__proto__ === u2.__proto__); //true
- console.log(u1.__proto__ === User.__proto__); //false
- console.log(User.prototype === u1.__proto__); //true
- console.log(User.prototype.__proto__ === Function.prototype.__proto__); //true
- console.log(User.__proto__ === Function.prototype); //true
- console.log(User.__proto__ === Function.__proto__); //true
- console.log(Object.__proto__ == Function.prototype); //true
- console.log(Function.prototype == Function.__proto__); //true
- console.log(Function.prototype.__proto__ === Object.prototype); //true
- console.log(Function.__proto__.__proto__ === Object.prototype); //true
数组很容易理解,但函数比较特殊,下面是它的图示: