[Javascript] Prototype, hasOwnProperty(), valueOf() and toString() methods.

Sometime, use can rewrite the toString , valueOf method to make those function more useful:

For exmaple, we can make valueOf() function to calcualte the sum, and then use toString method to display the information of the object we create.

var Tornado = function(category, affectedAreas, windGust){
    this.category = category;
    this.affectedAreas = affectedAreas;
    this.windGust = windGust;
};

var cities = [["Kansas City", 46310],["Topeka", 127939],["Lenexa", 49398]];
var twister = new Tornado("F5", cities, 220);
cities.push(["Olathe", 130045]);
twister.toString();

Tornado.prototype.toString = function(){
    var list = "";
    for(var i = 0; i< this.affectedAreas.length; i++){
        if(i < this.affectedAreas.length-1){
            list = list + this.affectedAreas[i][0] + ", ";
        }else{
            list = list + "and "+ this.affectedAreas[i][0];
        }
    }
    return "This tornado has been classified as an " + this.category+
    ", with wind gusts up to "+ this.windGust+ "mph. Affected areas are:"+
    list+", potentially affecting a population of "+ this.valueOf() + ".";
};

Tornado.prototype.valueOf = function(){

    var sum = 0;
    for(var i = 0; i < this.affectedAreas.length; i++){
        sum += this.affectedAreas[i][1];
    }
    return sum;
}

Object.prototype.findOwnProperty = function(propName){
    var currentObject = this;
    while(currentObject !== null){
        if(currentObject.hasOwnProperty(propName)){
            return currentObject;
        }else{
            currentObject = currentObject.__proto__;
        }
    }
    return "No property found!";
}
twister.findOwnProperty("valueOf");
原文地址:https://www.cnblogs.com/Answer1215/p/3903806.html