如何制作包含点的功能

问题描述

我要创建一个名为“ lib.hello”的函数,该函数是有效的语法,如果没有,我该怎么做? 这是我的代码function lib.hello(){ console.log("hello") }

function lib.hello(){
  console.log("hello")
}

解决方法

您可以这样做

function yourClass() {
}

yourClass.prototype.dotFunction = function() { return 'hello'; };

console.log(new yourClass().dotFunction());
,

首先,必须创建一个对象,然后再执行与波纹管相同的操作。

let Obj = {
  a:1,childMethod:(param)=>{console.log(param)}
}
Obj.childMethod("test")

或者您可以通过以下代码来做到这一点:

function yourClass() {
}

yourClass.prototype.childMethod = function(parameter) { console.log(parameter); };

var a = new yourClass();
a.childMethod("test");

//or you can do it same as follow

new yourClass().childMethod("test2")

,

您为什么要这样做?这似乎是XY Problem或理论上的练习。

正如其他答案所暗示的那样,您可以使用名为lib的方法来创建名为hello的类,但这与名为lib.hello的函数并不完全相同。

这是另一种变化:

let a = {
    'lib.hello' : function() {
        console.log('hello');
    }
}

a['lib.hello']()

从技术上讲,这是一个匿名函数,而不是名为lib.hello的函数,但这有点像您要的,因为它与键lib.hello关联。