Javascript笔记(Day02)

1、日常开发中,一般使用构造函数与原型结合的方式,构造函数用于定义实例属性,原型对象用于定义方法和要共享的属性。这样每个实例都会拥有一份实例的副本并且又有共享的内容,极大节省了内存。

function Sll(name, age, bf){
    this,name = name;
    this.age = age;
    this.bf = ['cty'];
}
Sll.prototype = {
    constructor: Sll,
    sayName(){
        console.log('我家傻萝莉是智障障...');
    }
}
const sll = new Sll('yjm', 21);
const zzz = new Sll('loly', 22);
sll.bf.push('大叔');
console.log(sll.bf,zzz.bf); //[ 'cty', '大叔' ] [ 'cty' ]

2、寄生构造函数方式,类似于工厂模式,创建一个表面上像是构造函数的函数,但仅仅用来封装创建对象,并返回新创建的对象。(注意,不能用instanceof来确定对象类型)

function Sll(name, age){
    const o = new Object();
    o.name = name;
    o.age = age;
    return o;
}
const yjm = new Sll('mdzz', 21);
console.log(yjm.name);//mdzz

例子: 假设我们需要创建一个具有额外方法的数组,因为不能在Array构造函数上修改。

function ExtraArray(){
    const arr = new Array();
    arr.push.apply(arr, arguments);
    arr.extraFunction(){
        return this.join('+');
    }
    return arr;
}
const arrayTest = new ExtraArray('sll', 'is', 'zzz');
console.log(arrayTest.extraFunction());//sll+is+zzz

3、原型链(继承),这个东西直接上代码吧

function Father(){
    
}
Father.prototype.getFather = function(name){
    console.log(name);
}
function Child(){

}
Child.prototype = new Father();
Child.prototype.getChild = function(child){
    console.log(child);
}
const child1 = new Child();
child1.getChild('yjm');//yjm
child1.getFather('cty');//cty
function GrandChild(){

}
GrandChild.prototype = new Child();
GrandChild.prototype.getGrandChild = function(grandChild){
    console.log(grandChild);
}
const grandChild1 = new GrandChild();
grandChild1.getFather('ctyzz');//ctyzz
grandChild1.getChild('yjmzz');//yjmzz
grandChild1.getGrandChild('mdzz');/mdzz
console.log(grandChild1 instanceof Father, grandChild1 instanceof Child, grandChild1 instanceof GrandChild);//true true true

GrandChild继承Child,Child继承Father,所以GrandChild的实例grandChild1也是Child、Father的实例,所以代码中三个instanceof结果都是true。
(注意,不能用对象字面量的形式创建原型方法,不然会重写原型链。)

***.prototype = {
    //function
    //function
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原型链是一种机制,指的是 JavaScript 每个对象都有一个内置的 __proto__ 属性指向创建它的构造函...
    劼哥stone阅读 9,887评论 15 80
  • 第5章 引用类型 引用类型的值(对象)是引用类型的一个示例。在ECMAScript 中,引用类型是一种数据结构,用...
    力气强阅读 4,014评论 0 0
  • 夜里十一点,立早还在忙着赶路。 白灯笼摇曳着微弱的烛光,立早一个人在赶路。 立早必须要在今天结束前见到她,因为凌晨...
    丶丨冲浪里阅读 1,501评论 0 0
  • 阳光轻抚着发梢 风吹来 带着温热的甜美, 多好 在这样的日子里 有我们的身影 follow your heart.
    薄雾迷殇阅读 1,521评论 0 0
  • 对照美洲13月亮历,红月年是2014年7月26日-2015年7月24日,而今天是红月年的最后一天。 按照月亮厉,我...
    三饭姨阅读 3,793评论 0 1