原型与原型链的区别?
原型是为了实现对象间的联系,解决构造函数无法数据共享而引入的一个属性,而原型链是一个实现对象间联系即继承的主要方法
原生实现继承
// 创建对象
function createObject(o){
function F(){}
F.prototype = o
return new F()
}
// 将subtype和supertype 联系在一起
function inherit(Sub,Super){
Sub.prototype = creatteObject(Subper.prototype)
Object.defineProperty(Sub.prototype,"constructor",{
enumerable:false,
configurable:true,
writable:true,
value:Sub
})
Object.setPrototypeOf(Sub,Super)
}
// 使用
function Person(name,age,height){
this.name = name
this.age = age
this.height = height
}
Person.prototype.runnning = function (){
console.log("running~")
}
Person.prototype.eating = function(){
console.log("eating")
}
function Student(name.age,height,sno,score){
// 属性的继承
Person.call(this,name,age,height)
this.sno = sno
this.score = score
}
// 方法的继承
inherit(Student,Person)
Student.prototype.studying = function(){
console.log("studying")
}
// 创建实例
var stu1 = new Student("why",18,1.33,222,222)
class如何使用?
var names = ["abc", "cba", "nba", "mba"]
class Person { // 类的结构
// 类的构造函数
// 当我们通过new关键字调用一个person类时,默认调用的class中constructor方法
constructor(name,age,gzname){
this.name = name
this.age = age
this._gzname = gzname
- List item
}
// 实例方法
// 本质上放在person.prototype
running(){}{
console.log(this.name + 'running~')
}
eating(){}{
console.log(this.name + 'eating~')
}
set gzname(value){
console.log("设置gzname")
this._gzname = gzname
}
get gzname(){
console.log("获取gzname")
retrun this._gzname
}
// 类方法(静态方法)
static randomPerson(){ // 只有添加了static 才可以person.randomPerson 直接调用,否则就会报错is not a function
console.log("this",this)
var randomName = names[Math.floor(Math.random()*names.length)]
return new this(randomName.Math.floor(Math.random()*100))
}
static sleep(){
console.log("static sleep")
}
}
// 创建实例对象
var p1 = new Person()
p1.gzname = "dsddd"
console.log(p1.gzname )
// 与原生的对比 class不可以作为一个作为一个普通函数调用
class Student extends Person { // extends 子类student继承person父类的属性与方法
consstructor(name, age,gzname, sno, score){
super(name,age,gzname) // 必须写在子类属性的前面否则会报没有写在前的错误
this.sno
this.score = score
}
studying(){
// 如果跟父类的方法名称一样就近原则,调用子类的
console.log("studying~")
}
running(){
console.log("运动")
super.running() // 添加后会继承父类的部分方法
}
static sleep(){
console.log("睡觉")
super.sleep()
}
}
class 类的混入
function mixinAnimal(BaseClass){
return class extends BaseClass {
running(){
console.log("runniing")
}
}
}
function mixinRunner(BaseClass){
return class extends BaseClass {
flying(){
console.log("flying")
}
}
}
class Bird{
eating(){
console.log("eating")
}
}
class NewBird exends mixinRunner(mixinAnimal(Bird)){ }
var bird = new NewBird()
bird.flying()
bird.running()
bird.eating()