JavaScript中对象调用自身的原型方法

来源:互联网 发布:手机淘宝推广平台 编辑:程序博客网 时间:2024/05/18 15:56

//创建构造函数

function Foo(){ }

//添加公有方法,即添加原型方法

Foo.prototype.bar = function(){

alert('hello');

}

创建Foo的实例后,实例可以直接调用原型方法 .bar(),但是对象Foo不能直接调用原型方法.bar()。

var f = new Foo('hello');

f.bar();// hello

Foo.bar(); //undefined

 

让Foo对象调用.bar 方法,在中间加上prototype 即可。

Foo.prototype.bar();  // hello

原创粉丝点击