构造函数实例属性和方法
function Person() {
this.name = '李狗蛋'
this.run = function () {
console.log(this.name)
}
}
Person.prototype.age = 20
Person.prototype.foo = function () {
console.log(this.name + 'foo')
}
Person.sex = '男'
Person.boo = function () {
console.log('静态方法boo')
}
console.log(Person.sex)
Person.boo()
var p = new Person()
console.log(p.name)
console.log(p.age)
p.run()
p.foo()
继承 原型链+对象冒充模式
对象冒充模式
function Person() {
this.name = '李狗蛋'
this.run = function () {
console.log(this.name)
}
}
Person.prototype.age = 20
Person.prototype.foo = function () {
console.log(this.name + 'foo')
}
function Student() {
Person.call(this)
}
var s = new Student()
s.run()
s.foo()
原型链模式
function Person() {
this.name = '李狗蛋'
this.run = function () {
console.log(this.name)
}
}
Person.prototype.age = 20
Person.prototype.foo = function () {
console.log(this.name + 'foo')
}
function Student() {}
Student.prototype = new Person()
var s = new Student()
s.run()
s.foo()
原型链模式的问题
function Person(name) {
this.name = name
this.run = function () {
console.log(this)
console.log(this.name + '在工作')
}
}
Person.prototype.age = 20
Person.prototype.foo = function () {
console.log(this.name + 'foo')
}
function Student(name) {}
Student.prototype = new Person()
var s = new Student('李狗蛋')
s.run()
原型链+对象冒充组合模式
function Person(name) {
this.name = name
this.run = function () {
console.log(this.name + '在工作')
}
}
Person.prototype.age = 20
Person.prototype.foo = function () {
console.log(this.name + 'foo')
}
function Student(name) {
Person.call(this, name)
}
Student.prototype = new Person()
Student.prototype = Person.prototype
var s = new Student('张翠花')
s.run()
s.foo()