JavaScript学习总结(五)

之前的几讲中我们曾经说过,JavaScript中是没有类的概念的。但是我们讲过对象,那么这个对象是怎么来的呢?
只要有函数即可创建对象

自定义对象

自定义对象的方式:
1. 使用无参的函数创建对象

<script type="text/javascript">
    function Person(){}

    var p = new Person();
    //直接调用对象向对象中插入元素
    p.id = 123;
    p.name = "大熊";
    //插入方法元素时的操作
    p.say = function(){
        alert("我的名字叫做"+p.name);
    }
    document.write("编号:"+p.id + "姓名:"+p.name);
    p.say();

</script>

如果再使用Person创建一个对象, 此时的对象不具备之前对象添加的元素。
2. 使用带参的函数创建对象

function Person(id,name){
    this.id = id;
    this.name = name;   
    this.say = function(){
        alert(name+"666");  
    }
}

这种方式和java中的构造方法类似,很好学,对吧。
3. 使用Object函数创建对象

var p = new Object();
p.id = 123;
p.name = "大熊";

4. 使用字面量的方式创建

var p = {
    id:123,
    name:"大熊",
    say:function(){
        alert(this.name+"666"); 
    }   
}   

prototype原型

现在我们有这样一个需求,我们想给Array对象添加一些新的方法,但是正常的思路就是自定义一个工具对象,调用的时候先新建一个工具对象,将数组作为参数传入方法。这样其实是很麻烦的,为了简化操作,我们就用到了原型,使得方法可以直接用数组对象调用。
那么,什么是prototype原型呢?prototype是函数(function)的一个必备属性(书面一点的说法是”保留属性”)(只要是function,就一定有一个prototype属性)
prototype的特性如下:

  • prototype的值是一个对象
  • 可以任意修改函数的prototype属性的值
  • 一个对象会自动拥有prototype的所有成员属性和方法

具体使用方法如下代码:

    Array.prototype.getMax = function(){
        var max = this[0];
        for(var index = 1; index<this.length ; index++){
            if(this[index]>max){
                max = this[index];  
            }   
        }
        return max;
    }
    Array.prototype.searchEle = function(target){
        for(var i = 0 ; i<this.length ; i++){
            if(target==this[i]){
                return i;   
            }   
        }
        return -1;
    }
    //var arr = new Array(12,4,17,9);
    var arr = [12,4,17,9];
    var max = arr.getMax();
    var index = arr.searchEle(9);
    document.write("最大值:"+ max+"<br/>");
    document.write("索引值:"+ index+"<br/>");

练习:给字符串对象添加一个toCharArray的方法,然后再添加一个reverse(翻转)的 方法

//先创建一个prototype对象(指向Object)
function String(){
    this.prototype = new Object();
}

//使用原型
String.prototype.toCharrArray = function(){
    var arr = new Array();
    for(var i=0;i<this.length;i++){
        arr[i] = this.charAt(i);
    }
    return arr;
}

String.prototype.reverse = function(){
    var arr = this.toCharrArray();
    arr.reverse();
    return arr.join(",");
}

至此,JavaScript的基本语法所有内容介绍完毕。下面的几讲中我们将介绍其余两个部分的内容。

原文地址:https://www.cnblogs.com/roobtyan/p/9576722.html