在javascript中向原型和对象文字添加函数之间的区别 [英] Difference between adding function to prototype and object literal in javascript

查看:64
本文介绍了在javascript中向原型和对象文字添加函数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个构造函数Quo

var Quo = function (string) {
     this.status = string;
};

然后使用 var myQuo = new Quo("confused");

有什么区别:

Quo.get_status = function () { 
    return this.status;
};

Quo.prototype.get_status = function () { 
    return this.status;
};

推荐答案

假设您已经按照您的描述创建了 myQuo

Let's suppose you have created myQuo, as you described

var myQuo = new Quo("confused");

如果您将 get_status 定义为 Quo 的属性,那么要获取 myQuo 的状态,您必须调用 Quo.get_status.但是,Quo.get_status 需要知道对象上下文 (myQuo) 才能返回正确的状态值.您可以重新定义函数以接受对象作为参数,如下所示:

If you define get_status as a property of Quo, then to get the status of myQuo you would have to call Quo.get_status. However, Quo.get_status will need to know the object context (myQuo) to return the correct value of status. You can redefine the function to accept the object as an argument as in the following:

Quo.get_status = function (quo) { 
  return quo.status;
};
var status = Quo.get_status(myQuo);

或者,您可以保留在问题中编写的函数 Quo.get_status,但您需要以将 myQuo 绑定到的方式调用该函数这个":

Alternatively, you could keep the function Quo.get_status as you wrote it in your question, but you will need to invoke the function in a manner that binds myQuo to "this":

Quo.get_status = function() {
  return this.status;
};
var status = Quo.get_status.call(myQuo);

这两种解决方案都很尴尬.首选的解决方案是利用 Javascript 的原型功能并将 get_status 定义为所有 Quo 对象(例如 myQuo.

Either solution is awkward. The preferred solution is to take advantage of Javascript's prototype functionality and define get_status as a prototype function that will be locally accessible to all Quo objects, such as myQuo.

Quo.prototype.get_status = function () { 
  return this.status;
};
var status = myQuo.get_status();

这篇关于在javascript中向原型和对象文字添加函数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆