基本上,ES6 的class能够看做只是一个语法糖,它的绝大部分功能,ES5 均可以作到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。编程
function Person () {
this.name = 'person1'
}
Person.prototype.sex = '10'
Person.prototype.sayName = function () {
alert(this.name)
}
function Man () {
Person.call(this)
this.age = '24'
}
var m1 = new Man()
console.log(m1) // Man {name: "person1", age: "24"} (注意:实例自身不存在sex属性和
sayName方法)
// m1.sayName() // 报错 (由于原型链上也不存在)
复制代码
function Father () {
this.Farr = [1, 2, 3]
}
function Child () { }
Child.prototype = new Father()
var c1 = new Child()
var c2 = new Child()
console.log(c1.Farr) // [1, 2, 3]
console.log(c2.Farr) // [1, 2, 3]
c1.Farr.push(4)
console.log(c1.Farr) // [1, 2, 3, 4]
console.log(c2.Farr) // [1, 2, 3, 4]
复制代码
function Mother () {
console.log('init Mother...')
this.Marr = ['a', 'b', 'c']
}
function Daughter () {
Mother.call(this) // 执行一次Mother构造函数
}
Daughter.prototype = new Mother() // 再执行一次Mother构造函数
var d1 = new Daughter()
var d2 = new Daughter()
console.log(d1.Marr) // ["a", "b", "c"]
console.log(d2.Marr) // ["a", "b", "c"]
d1.Marr.push('d')
console.log(d1.Marr) // ["a", "b", "c", "d"]
console.log(d2.Marr) // ["a", "b", "c"]
console.log(d2.__proto__.constructor === Mother) // true(指望值是false,由于Daughter才是d2的直接父类)
复制代码
function Animal () {
console.log('init Animal...')
}
function Cat () {
Animal.call(this) // 执行一次Animal构造函数
}
Cat.prototype = Animal.prototype
var cat = new Cat()
console.log(cat.__proto__.constructor === Animal) // true(指望值是false,由于Cat才是cat的直接父类)
复制代码
function God () {
console.log('init Final...')
this.name = 'god'
}
God.prototype.todo = function () {
alert('todo')
}
function Son () {
God.call(this)
}
// Son.prototype = God.prototype
Son.prototype = Object.create(God.prototype) // Object.create()方法建立一个新对象,使用现有的对象来提供新建立的对象的__proto__
console.log(God.prototype)
console.log(Object.create(God.prototype))
Son.prototype.constructor = Son
var s = new Son // 无参数时,小括号能够省略
console.log(s)
console.log(s.__proto__.constructor === Son) // true (与指望值一直,完美!)
console.log(s.__proto__.constructor) // true (与指望值一直,完美!)
复制代码
// 普通方法建立对象的对象
console.log({})
// 使用Object.create建立的对象
console.log(Object.create(null))
// 使用Object.create,会将现有对象放到__proto__属性中
function God () {
console.log('init Final...')
this.name = 'god'
}
God.prototype.todo = function () {
alert('todo')
}
function Son () {
God.call(this)
}
// Son.prototype = God.prototype
Son.prototype = Object.create(God.prototype)
Son.prototype.constructor = Son
console.log(Son.prototype)
复制代码
普通方法建立对象的对象 函数
使用Object.create建立的对象 优化
使用Object.create()方法实现继承 ui
不使用Object.create()方法实现继承 this
本篇完。spa