new是干什么的
https://zhuanlan.zhihu.com/p/23987456

  1. function Human({
  2. name,
  3. city
  4. }) {
  5. this.name = name;
  6. this.city = city;
  7. }
  8. Human.prototype.constructor = Human
  9. Human.prototype.species = '人类'
  10. Human.prototype.walk = function () {
  11. console.log(this.name + 'walk')
  12. }
  13. Human.prototype.useTools = function () {
  14. console.log(this.name + 'useTools')
  15. }
  16. export default Human;
  1. import Human from './Human';
  2. var human = new Human({
  3. name: 'Frank',
  4. city: 'Hangzhou'
  5. })
  6. console.log(human.walk())
  7. console.log(human.__proto__.constructor === Human)

构造函数

构造函数就差不多是自定义的包装类

JavaScript 语言使用构造函数(constructor)作为对象的模板。所谓”构造函数”,就是专门用来生成实例对象的函数。它就是对象的模板,描述实例对象的基本结构。一个构造函数,可以生成多个实例对象,这些实例对象都有相同的结构

  1. var Vehicle = function () {
  2. this.price = 1000;
  3. };
  4. var v = new Vehicle();
  5. v.price // 1000

原型链

  1. var Vehicle = function () {
  2. this.price = 1000;
  3. };
  4. var v = new Vehicle();
  5. v
  6. Vehicle {price: 1000}price: 1000__proto__: Object
  7. v.__proto__ === Vehicle.prototype
  8. true
  9. Vehicle.prototype.__proto__ === Object.prototype
  10. true

使用new命令时,它后面的函数依次执行下面的步骤。

  • 创建一个空对象,作为将要返回的对象实例。
  • 将这个空对象的原型,指向构造函数的prototype属性。
  • 将这个空对象赋值给函数内部的this关键字。
  • 开始执行构造函数内部的代码。
  1. function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) {
  2. // 将 arguments 对象转为数组
  3. var args = [].slice.call(arguments);
  4. // 取出构造函数
  5. var constructor = args.shift();
  6. // 创建一个空对象,继承构造函数的 prototype 属性
  7. var context = Object.create(constructor.prototype);
  8. // 执行构造函数
  9. var result = constructor.apply(context, args);
  10. // 如果返回结果是对象,就直接返回,否则返回 context 对象
  11. return (typeof result === 'object' && result != null) ? result : context;
  12. }
  13. // 实例
  14. var actor = _new(Person, '张三', 28);

如果构造函数内部有return语句,而且return后面跟着一个对象,new命令会返回return语句指定的对象;否则,就会不管return语句,返回this对象

  1. var Vehicle = function (){
  2. this.price = 1000;
  3. return { price: 2000 };
  4. };
  5. (new Vehicle()).price
  6. // 2000

Object.create() 创建实例对象

构造函数作为模板,可以生成实例对象。但是,有时拿不到构造函数,只能拿到一个现有的对象。我们希望以这个现有的对象作为模板,生成新的实例对象,这时就可以使用Object.create()方法

  1. var person1 = {
  2. name: '张三',
  3. age: 38,
  4. greeting: function() {
  5. console.log('Hi! I\'m ' + this.name + '.');
  6. }
  7. };
  8. var person2 = Object.create(person1);
  9. person2.name // 张三
  10. person2.greeting() // Hi! I'm 张三.

原型链

  1. var person1 = {
  2. name: '张三',
  3. age: 38,
  4. greeting: function() {
  5. console.log('Hi! I\'m ' + this.name + '.');
  6. }
  7. };
  8. var person2 = Object.create(person1);
  9. person2.name
  10. "张三"
  11. person2.__proto__ === person1.prototype
  12. false
  13. person2.__proto__ === person1
  14. true
  15. person1.__proto__ === Object.prototype
  16. true