创建自定义类型方式

前提是你 提交于 2020-01-09 19:22:12

1、 构造函数和原型函数

function Money(value,name,count){
    this.value = value;
    this.name = name;
    this.count = count;
}
Money.prototype = {
    constructor:Money,
    getMoney : function(){
        return this.value * this.count;
    }
}
mon.getMoney()  ===> 100

2、动态原型模式
(此方法不能重写构造函数原型,否则对象获取不到新增属性或方法)

在这里插入图片描述

function Money1(value,name,count){
    this.value = value;
    this.name = name;
    this.count = count;
    if(typeof this.some != "function"){
        Money1.prototype.some = 222;
        console.log("打印出:" +123456)
    }
}
let mo2 = new Money1(10,'kk',1); ====打印出:123456

3、寄生构造函数
想拥有一个新的方法,但是不能直接改变引用类型的构造函数。

function someTime(){
    let arr = new Array();
    arr.push.apply(arr,arguments);
    arr.toJion = function(){
        return this.join("|")
    }
    return arr}
undefined
let arr = new someTime("11",22,44,55,66);
 ["11", 22, 44, 55, 66, toJion: ƒ]

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!