我怎样才能在函数对象中调用原型函数呢b

时间:2012-10-17 20:36:22

标签: javascript

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​func_obj();​

我正在努力让上面的代码工作。从我所看到的,这应该工作,不知道我在这里做错了什么。同时设置小提琴here

2 个答案:

答案 0 :(得分:2)

要使用this访问原型对象/方法,您必须创建func_obj的新实例。如果要访问带有实例的原型方法,则必须使用原型属性func_obj.prototype.my_proto_method()

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
   // if called without new then access prototype as : func_obj.prototype.my_proto_method()
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​new func_obj();​

答案 1 :(得分:2)

您需要使用新前缀:f / f>为func_obj添加前缀。

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​var foo = new func_obj();​
相关问题