CocosCreator 源码-polyfill/string详解

假如不知道prototype的同学,自行学习prototype的作用

【prototype 继承

所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法:

  • Date 对象从 Date.prototype 继承。

  • Array 对象从 Array.prototype 继承。

  • Person 对象从 Person.prototype 继承。

所有 JavaScript 中的对象都是位于原型链顶端的 Object 的实例。

JavaScript 对象有一个指向一个原型对象的链。当试图访问一个对象的属性时,它不仅仅在该对象上搜寻,还会搜寻该对象的原型,以及该对象的原型的原型,依次层层向上搜索,直到找到一个名字匹配的属性或到达原型链的末尾。

Date 对象, Array 对象, 以及 Person 对象从 Object.prototype 继承。

添加属性和方法

有的时候我们想要在所有已经存在的对象添加新的属性或方法。

另外,有时候我们想要在对象的构造函数中添加属性或方法。

使用 prototype 属性就可以给对象的构造函数添加新的属性:

function Person(first, last, age, eyecolor) {  this.firstName = first;  this.lastName = last;  this.age = age;  this.eyeColor = eyecolor;} Person.prototype.nationality = "English";

当然我们也可以使用 prototype 属性就可以给对象的构造函数添加新的方法:

function Person(first, last, age, eyecolor) {  this.firstName = first;  this.lastName = last;  this.age = age;  this.eyeColor = eyecolor;} Person.prototype.name = function() {  return this.firstName + " " + this.lastName;};

if (!String.prototype.startsWith) {

    String.prototype.startsWith = function (searchString, position) {

        position = position || 0;

        //查找的字符串的最后一个匹配是否等于0,假如是,就是以该字符串开头,否则则不是

        return this.lastIndexOf(searchString, position) === position;

    };

}

//eg: hello world .endwith(world);

if (!String.prototype.endsWith) {

    String.prototype.endsWith = function (searchString, position) {

        //当位置参数为undefined的时候 或者位置大于字符串的长度,默认为最后一个字符的位置

        if (typeof position === 'undefined' || position > this.length) {

            position = this.length;

        }

        //更新position位置,传入位置减去要查找字符串的长度;

        position -= searchString.length;

        //indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。如果没有找到匹配的字符串则返回 -1。

        /* 语法

        string.indexOf(searchvalue,start)

        参数值

        参数 描述

        searchvalue 必需。规定需检索的字符串值。

        start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string Object.length - 1。如省略该参数,则将从字符串的首字符开始检索。*/

        //判断要查找的字符串开始的位置

        var lastIndex = this.indexOf(searchString, position);

        //查找的字符串等于总长度减去查找字符串的长度,是则返回true,否则 false

        return lastIndex !== -1 && lastIndex === position;

    };

}

if (!String.prototype.trimLeft) {

    //通过正则替换,把左侧空格干掉;

    /* 

    正则里面 \s 指的是 --匹配任何空白字符,包括空格、制表符、换页符等等。,

    匹配任何空白字符,包括空格、制表符、换页符等等。

    加号匹配任何空白字符,包括空格、制表符、换页符等等。*/

    String.prototype.trimLeft = function () {

        return this.replace(/^\s+/, '');

    };

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值