在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();