对象方法
function Person(name){
this.name = name;
this.Intro = Intro;
}
function Intro(){
console.log(this.name);
}
类方法
Person.run = function(){//不需要创建实例就能调用
console.log(this.name + " is running.");
}
调用方法:
Person.run();//实例并不能访问这个方法
原型方法
Person.prototype.IntroInterst=function(){
console.log(this.name+" "+"loves running.");
}
原型方法需要实例化后才能调用。
完整代码
function Person(name){
this.name = name;
this.Intro = Intro;//对象方法
}
function Intro(){
console.log(this.name);
}
Person.run = function(){//类方法
console.log(this.name + " is running.");
}
Person.prototype.IntroInterest= function(){
};
var jack = new Person("Jack");//jack没有run方法。
console.log(Object.getOwnPropertyNames(Person));
console.log(Object.getOwnPropertyNames(jack));//jack没有run方法
Q:类方法的作用是什么?
类似于私有属性。同时var定义的也是私有的属性。
小结:
类方法不需要实例化就可以调用,类似于私有属性or方法。
联想到js的函数有一部分是Object.func(),另一部分是Object.prototype.func()。