一、构造函数
构造函数与普通函数唯一的区别就是调用方式不同。除此之外,构造函数也是函数。并没有把某个 函数定义为构造函数的特殊语法。任何函数只要使用 new 操作符调用就是构造函数,而不使用 new 操 作符调用的函数就是普通函数。
function Person(name, age, job) {this.name = name;this.age = age;this.job = job;this.sayName = function() { alert(this.name) }}// person1 和 person2 都是 Person 的实例var person1 = new Person('phy', 28, 'developer');var person2 = new Person('zsl', 28, 'Doctor');// 实例的构造函数属性(constructor)指向构造函数。console.log(person1.constructor === Person); //trueconsole.log(person2.constructor === Person); //true
二、原型对象
无论何时,只要创建一个函数,就会按照特定的规则为这个函数创建一个 prototype 属性(指向 原型对象)。
console.log(typeof Function.prototype) // Function,这个特殊console.log(typeof Object.prototype) // Objectconsole.log(typeof Function.prototype.prototype) //undefined
三、proto(隐式原型)
实例通过proto链接到原型对象
let a = 1;console.log(a.__proto__ === Number.prototype) // trueconsole.log(a.__proto__.__proto__ === Object.prototype) // trueconsole.log(a.__proto__.__proto__.__proto__ === null) // truelet b = function(){};console.log(b.__proto__ === Function.prototype) // trueconsole.log(b.__proto__.__proto__ === Object.prototype) // trueconsole.log(b.__proto__.__proto__.__proto__ === null) // true
四、构造器
Number.__proto__ === Function.prototype // trueNumber.constructor == Function //trueBoolean.__proto__ === Function.prototype // trueBoolean.constructor == Function //trueString.__proto__ === Function.prototype // trueString.constructor == Function //true// 所有的构造器都来自于Function.prototype,甚至包括根构造器Object及Function自身Object.__proto__ === Function.prototype // trueObject.constructor == Function // true// 所有的构造器都来自于Function.prototype,甚至包括根构造器Object及Function自身Function.__proto__ === Function.prototype // trueFunction.constructor == Function //trueArray.__proto__ === Function.prototype // trueArray.constructor == Function //trueRegExp.__proto__ === Function.prototype // trueRegExp.constructor == Function //trueError.__proto__ === Function.prototype // trueError.constructor == Function //trueDate.__proto__ === Function.prototype // trueDate.constructor == Function //true
JavaScript中有内置(build-in)构造器/对象共计12个(ES5中新加了JSON),这里列举了可访问的8个构造器。剩下如Global不能直接访问,Arguments仅在函数调用时由JS引擎创建,Math,JSON是以对象形式存在的,无需new。它们的proto是Object.prototype。如下
Math.__proto__ === Object.prototype // trueMath.construrctor == Object // trueJSON.__proto__ === Object.prototype // trueJSON.construrctor == Object //true
N、new操作符
- 在内存中创家奴一个新对象。
- 这个新对象内部的prototype特性被赋值为构造函数的prototype属性。
- 构造函数内的this被赋值为这个新对象(即this指向新对象)。
- 执行构造函数内部的代码(给新对象添加属性)。
- 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象。
参考链接
