Sunday, November 20, 2016

Adding Methods to a Prototype

Using the prototype Property
The JavaScript prototype property allows you to add new properties to an existing prototype:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English"
 Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
}; 
 Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
-------------------------------------------------------------------- 
就是调用对象是一个Array,对Array类型增加了一个原型写法的函数,一般写一些扩展时经常用。比如判断一个元素是否在数组中之类的
Array.prototype.inArray=function(value){
   for(var i=0;i<this.length;i++){
       if (this[i] == value){
       return true;
       }
   }
return false
};
var arr=["1","2","3"];
//以下同调用方式,在inArray函数中,使用this即可得到arr
arr.inArray("1");

No comments:

Post a Comment