大家好,又见面了,我是你们的朋友全栈君。
js的方法可以分为三种:对象方法、类方法、prototype方法
//对象方法 function People(name){ this.name=name; this.introduct=function(){ alert(“My name is”+this.name); console.log(“My name is”+this.name); } }
//类方法 People.Run=function(){ alert(“I can run”); } console.log(People.Run()); //原型方法 People.prototype.introduceChinese=function(){ alert(“我的名字是”+this.name); }
这里要注意类方法只能通过类名.方法名调用,实例方法只能通过实例名.方法名调用,反之不可以
还有prototype是类的属性,new出来的对象是没有这个属性的,比如People.prototype可以,var p=new People(); p.prototype不可以
function Aclass2(){ this.property=2; this.method=function(){ alert(2); } }
function Aclass(){ this.property=1; this.method=function(){ alert(1); } }
子类重写父类的属性和方法,要注意不能修改父类的属性和方法,可以这样写Aclass2.prototype=new Aclass(); 把父类的一个实例对象赋值给子类的prototype属性,我们调用实例对象的时候,首先会调用构造函数的属性和方法,然后是 prototype中写的和父类的属性和方法
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163359.html原文链接:https://javaforall.cn