参考

https://www.runoob.com/js/js-object-prototype.html

直接代码说话吧:

function person() {}
person.prototype.test = function () {
  console.log(this.a)
}

let per1 = new person()
per1.a = '456'
per1.test()   // 456
person.prototype.test() //undefined

per1.test = function () {
  console.log('123')
}
per1.test()  //123
per1.prototype.test() //TypeError: Cannot read property 'test' of undefined



通过上面代码可以看出:

1、当对象实例可以有test函数的时候,就执行当前的test函数 。如果找不到的话,就去prototype上面去找。

2、在对象实例上面无法直接调用prototype对象

per1.__proto__

另外我们可以看下person对象在运行时候的堆栈信息。

typescript之prototype_typescript

第一个test 应该是当前实例上的函数,第二个test是prototype上面的test函数。

per1.__proto__.test()   //undefined

上述的方法也可以调用prototype上面的test对象,但是获取不到this.a的值,这个应该是当前的this指向了__proto__对象了。

这里还有一种用法,如下:

person.test2 = function () {
  console.log('test2')
}
person.test2() //test2
per1.test2()   //TypeError: per1.test2 is not a function

这种用法的话,那么test2函数和我们实例的对象就完全没有关系了。只可以在person函数上面调用。