[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");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值