第十二课:类中创建方法
在类中创建一个方法
方式一:在类内写方法
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();//所有字符串都可以调用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步