问题描述
如果我有一个名为 format
的变量和一个同名的方法,我将如何调用该变量和方法?
If I have a variable named format
and a method with the same name, how would I go about calling the variable, and the method?
use strict;
function Time() {
this.format = 'x:y:z';
}
Time.prototype = {
format: function (format) {
}
}
推荐答案
您通常不能这样做,因为在 JavaScript 中,方法 和包含功能——它们完全一样!您可以通过将函数分配给属性来创建方法.
You can't usually do this, because there is no difference in JavaScript between a method and a property containing a function -- they are exactly the same thing! You create methods by assigning functions to properties.
在这种特殊情况中,您可以通过原型访问函数对象并将其应用于对象,但这是一个可怕的 hack.
In this particular case, you can access the function object through the prototype and apply it to the object, but this is a terrible hack.
Time.prototype.format.apply(some_time_object);
最好将方法和值存储在不同名称的属性中.
You would be better off storing the method and the value in differently-named properties.
这篇关于区分同名的属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!