Js面向对象的四层 -Axel Rauschmayer

四个层次

第一层 单一对象

创建对象

  • 对象:字符和数值的映射

  • 属性:访问映射

  • 方法:属性的值是函数

    • this 指向函数的接受者

var jane ={
    //属性
    name='Jane',
    
    //方法
    describe:function(){
        return 'Person named'+this.name;
    }

https://www.youtube.com/watch?v=VJOTcUsD2kA&t=6m16s

对象和映射(map)

相同点:
  • 非常动态:自由删除增加属性

不同点:
  • 继承(原型链继承)

  • 快速访问属性(通过构造器器)

第二层 原型链 prototype chains

引出共享属性

var jane = {
    name:"jane",
    describe:function(){
        return 'Person named' +this.name;
    }

};

var tarzan = {
    name:'Tarzan',
    describe:function(){
        return 'Person named' + this.name;
    }
};

解决方案:通过原型继承

图片描述

  • jane 和 tarzan 通过共享一个原型对象。

  • 原型链和简单对象一样

var PersonProto ={
    describe:function(){
        return  'Person named' +this.name;
    }
}

var jane = {
    __proto__:PersonProto,
    name:'Jane'

};
var tarzan = {
    __proto__:PersonProto,
    name:'Tarzan'
};

获取和设置原型

  • es6: _proto _

  • es5:

    • Object.create()

    • Object.getPrototypeOf()

Obejct.create(proto):

var PersonProto = {
    decribe:function(){
        return 'Pseson named' + this.name;
    }
};

var jane = Object.create(PersonProto);
jane.name='Jane';

Object.getPrototypeOf(obj):

# Object.getPrototypeOf(jane) === PersonProto
true

第三层 构造器

persons的构造器

 function Person(name){
    this.name = name;
    this.decsribe = funciont(){
        return 'Person named' + this.name;
    };
 }
 
 var jane = new Person ('Jane');
 console.log(jane instanceof Person); //true

图片描述

如何消除冗余?
//特性的属性
 function Person(name){
    this.name = name;
 }
 
 //共享属性
 Person.prototype.describe = function(){
    return  'Person named'+ this.name;
 }

图片描述

instanceof是怎么工作的?

value instanceof Constr

检查 constructor.prototype是否在value的原型链上。
Constr.prototype.isPrototypeOf(value)

第四层 构造器的继承

目标: employee 继承 Person

function Person(name){
    this.name = name;
}
Person.prototype.sayHelloto = function (otherName){
    console.log(this.name +'says hello to' + otherName);
}
Person.prototype.describe = function(){
    return 'Person named' + this.name;
}

Employee(name,title)和Person一样,除了:

  • 其他属性:title

  • describe() return 'Person named <name> (<title>)'

为了继承,employee必须做:

  • 继承Person的属性

  • 创造属性title

  • 继承Person的原型属性

  • 重写Person.prototype.describe

function Employee (name,title){
    Person.call(this,name); //继承所有属性
    this.title = title ; //增加title属性
}
Employee.prototype = Object.create(Person.prototype);//继承原型属性
Employee.prototype.describe = function(){//重写原型describe
    return Person.prototype.describe.call(this)+ '('+this.title+')'; //重写方法
}

图片描述
图片描述

https://www.youtube.com/watch?v=VJOTcUsD2kA&t=6m16s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值