区分同名的属性和方法 [英] Differentiate between property and method with same name

查看:49
本文介绍了区分同名的属性和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个名为 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.

这篇关于区分同名的属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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