• [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");
  • 相关阅读:
    如何为惠普笔记本ProBook 4431S清理电源风扇通风口灰尘
    office app之 Mail App 从新建到发布
    sublime_text3汉化,破解,安装Package_control支持中文显示
    poj3126prime+BFS
    android开发之欢迎界面
    poj 1151 离散化
    DbVisualizer 9 解决中文乱码问题
    RS232、RS422与RS485串口标准简介
    动态创建菜单和动态关联菜单项事件
    更改路径
  • 原文地址:https://www.cnblogs.com/Answer1215/p/3903806.html
Copyright © 2020-2023  润新知