es6 class的constructor里面的方法和外面的方法有什么区别?

代码如下

/* A类,方法写在constructor里面 */
class A{
  constructor(){
    this.show = function (){
      console.log( 'A show' )
    }
  }
}

const a = new A()
a.show() // => A show

/* B类,方法写在constructor外面 */
class B{
  constructor(){
  }
  show(){
    console.log( 'B show' )
  }
}

const b = new B()
b.show()  // => B show

提问点

A类的show方法和B类的show方法调用结果都一样,那么请问写在constructor里和外面的区别是?

阅读 8.5k
3 个回答
const a1 = new A();
const a2 = new A();
console.log(a1.show === a2.show);// false

const b1 = new B();
const b2 = new B();
console.log(b1.show === b2.show);// true

B的show方法是在prototype上

一个是原型方法,一个是实例方法,实例方法【即写在constructor内的】在使用new关键字实例化的时候,new的内部实现中,会改变this指向,所以每个实例的show方法肯定不一样啊,只是同名而已。

    function Person(name) {
        this.name = name;
        this.run = function() {
            return '500m';
        }
    }
    Person.prototype.say = function() {
        return 'say: hello';
    }
    
    function _new(parent, ...args) {
        const obj = Object.create(parent.prototype);    // obj.__proto__ = parent.prototype
        const returnVal = parent.call(obj, ...args);     // 使用new实例化的时候,每次都会生成一个新对象,并且改变this指向,即parent中定义的show方法在obj这个对象上也有一份
        return typeof returnVal === 'object' ? returnVal : obj;
    }
    const man = _new(Person, 'man');    // 等同于 const man = new Person('man');

换成 es5 你就知道了。

写里面,等同于以下代码

function A(){
    this.show = function(){}
}

写外面

function A(){...}
A.prototype.show = function(){}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题