function Dialog(target) {
this.target = target
}
Dialog.prototype.show = function() {
console.log(this.target + ' show')
}
Dialog.prototype.hide = function() {
console.log(this.target + ' hide')
}
var dialog = new Dialog('body')
dialog.show()
function Message(target, name) {
Dialog.call(this, target) //这句很重要
this.name = name
}
Message.prototype = Object.create(Dialog.prototype) //这句更重要
Message.prototype.success = function() {
console.log(this.name + ' success' )
}
var msgBox = new Message('main', 'msg')
msgBox.show()
msgBox.success()
画成原型图
Dialog.call(this, target)
的作用是: 执行函数 Dialog(target),执行的过程中里面遇到 this 换成当前传递的 this
Object.create(Dialog.prototype)
的作用是:创建一个空对象,空对象的__proto__
等于 Dialog.prototype
Object.create 源码:
Object.create = function (a){
function Person(){
}
Person.protype=a//a赋值给Person.protype,相当于a替换了Person.protype
let b = new Person
return b
}
ES6
class Dialog{
constructor(target){
this.target = target
}
show(){
console.log(this.target + 'show')
}
hide(){
console.log(this.target + 'hide')
}
}
class Message extends Dialog{
constructor(target,name){
super(target)//如果是super()表示直接调用父类构造函数
//super必须在后面使用this之前
this.name = name
}
success(){
console.log(this.name + 'success')
}
}
var msgBox = new Message('main','msg')
msgBox.show()
msgBox.success()
console.log(msgBox)
网友评论