【问题标题】:JS How to create object by method "new" that can be called like functionJS如何通过可以像函数一样调用的“new”方法创建对象
【发布时间】:2019-04-04 14:24:16
【问题描述】:

我试图了解恶意 JS 脚本的作用。脚本混淆了,所以我自己看不懂。我知道它会创建一个 ActiveXObject 对象。

所以我决定用这个名字来声明我的对象,它只输出一个日志。 病毒使用构造

var x = new ActiveXObject('file_name')

Google 脚本 不允许您声明自己的类(是吗?),所以我为新的 AX 对象声明了一个构造函数。一切正常,直到病毒尝试像函数一样访问 AX 对象

var AX = new ActiveXObject()  
AX()

此返回类型不匹配(Object!=Function)。

那里有我的代码: https://script.google.com/d/1IrkYN_Sg0j_uiMD4fAmEPag3HLH07c1fd2t7QOQEphEg38R-t0LAPIAF/edit?usp=sharing

我注释第 195 行以防止出错。

运行函数 doGet 进行测试和查看日志。或者直接打开https://script.google.com/macros/s/AKfycbyiYp4kX07jMwjM6B0fynfMrqQwX1ykJHfy8wFpX6Op/dev

【问题讨论】:

  • 如果函数构造函数返回函数,你可以调用它。 function x() { return x; } 你打电话给(new x())() 甚至(new x())()()()()()()(new (new x()))。可能是用来迷惑读者的,不知道有没有其他情况,而且我对 ActiveX 的行为一无所知。
  • @jcubic,如果函数返回函数,而不是对象,那么构造函数新的创建函数。好的,那我可以像函数一样调用它,但我不能像对象一样调用它。所以我不能得到他的属性,不能调用他的方法。
  • 你可以给函数添加字段,因为函数只是对象。 function foo() { var bar = function(x) { console.log(x); }; bar.baz = 10; bar.quux = function() { return this.baz; }; return bar; } 并这样称呼它var x = new foo(); x('hello'); x.quux()
  • 但在这两种情况下,new 运算符都没有区别,无论有没有它,结果代码的行为都是一样的。因为我们没有在构造函数中使用 this。但是我们当然可以在 this 中创建对象并在内部函数中返回。 function foo() { this.y = 10; return () => this; } var x = new foo(); console.log(x() instanceof foo);
  • @jcubic 谢谢!这对我有用!

标签: javascript object google-apps-script


【解决方案1】:
function Foo(x){
  var res = function(a,b){
    //do something when call like function
    return a+b;
  };

  //add props & methods
  res.bar = x; //some prop
  res.add = function(a){return res.bar+=a} //some method
  res.quad = function(){return (res.bar*res.bar)} //other method

  return res; //return function with custom prop&methods
};

var foo = new Foo(1);

console.log(foo.bar); //1 
console.log(foo.add(2)); //3
console.log(foo.bar); //3
console.log(foo.quad()); //9
console.log(foo.bar); //3
console.log(foo(8,10)); //18 call like function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多