在类中创建一个方法

方式一:在类内写方法

  

function Product(pno,pname,price){
                //属性
                this.pno=pno;
                this.pname=pname;
                this.price=price;
                //方法
                this.getPrice=function(){
                    return this.price;
                }
            }
            
            var pro=new Product(111,"西瓜",4.0);//实例化类
            var pri=pro.getPrice();//调用类内方法
            alert(pri);//结果4.0

 

方式二:利用prototype给类动态扩展方法getPname()


function Product(pno,pname,price){
                //属性
                this.pno=pno;
                this.pname=pname;
                this.price=price;
                //方法
                this.getPrice=function(){
                    return this.price;
                }
            }
              //利用prototype给类动态扩展方法getPname()
            
            this.Product.prototype.getPname=function(){
                return this.pname;
            }
            
                //调用后期扩展的getPname()函数
                var pname=pro.getPname();
                alert(pname);//结果西瓜

 

扩展:给String类型扩展函数

//给String扩展一个方法(函数)
             String.prototype.suiyi=function(){
                 alert("这是给String类型扩展的衣蛾方法,叫做suiyi");
             }
            
             "abcd".suiyi();//所有字符串都可以调用