Подтвердить что ты не робот

Как расширить функцию с помощью классов ES6?

ES6 позволяет расширять специальные объекты. Таким образом, можно наследовать от функции. Такой объект можно назвать функцией, но как я могу реализовать логику для такого вызова?

class Smth extends Function {
  constructor (x) {
    // What should be done here
    super();
  }
}

(new Smth(256))() // to get 256 at this call?

Любой метод класса получает ссылку на экземпляр класса через this. Но когда он вызывается как функция, this относится к window. Как я могу получить ссылку на экземпляр класса, когда он вызывается как функция?

PS: Тот же вопрос на русском языке.

4b9b3361

Ответ 1

В вызове super будет вызываться конструктор Function, который ожидает строку кода. Если вы хотите получить доступ к своим данным экземпляра, вы можете просто указать его:

class Smth extends Function {
  constructor(x) {
    super("return "+JSON.stringify(x)+";");
  }
}

но это не очень удовлетворительно. Мы хотим использовать закрытие.

Если возвращенной функцией является замыкание, которое может получить доступ к вашему экземпляру, то переменные возможны, но нелегко. Хорошо, что вам не нужно вызывать super, если вы этого не хотите, вы все равно можете return произвольные объекты из ваших классов классов ES6. В этом случае мы сделали бы

class Smth extends Function {
  constructor(x) {
    // refer to `smth` instead of `this`
    function smth() { return x; };
    Object.setPrototypeOf(smth, Smth.prototype);
    return smth;
  }
}

Но мы можем сделать еще лучше и отвлечь эту вещь от Smth:

class ExtensibleFunction extends Function {
  constructor(f) {
    return Object.setPrototypeOf(f, new.target.prototype);
  }
}

class Smth extends ExtensibleFunction {
  constructor(x) {
    super(function() { return x; }); // closure
    // console.log(this); // function() { return x; }
    // console.log(this.prototype); // {constructor: …}
  }
}
class Anth extends ExtensibleFunction {
  constructor(x) {
    super(() => { return this.x; }); // arrow function, no prototype object created
    this.x = x;
  }
}
class Evth extends ExtensibleFunction {
  constructor(x) {
    super(function f() { return f.x; }); // named function
    this.x = x;
  }
}

По общему признанию, это создает дополнительный уровень косвенности в цепочке наследования, но это не обязательно плохо (вы можете расширить его вместо нативного Function). Если вы хотите избежать этого, используйте

function ExtensibleFunction(f) {
  return Object.setPrototypeOf(f, new.target.prototype);
}
ExtensibleFunction.prototype = Function.prototype;

но обратите внимание, что Smth не будет динамически наследовать статические свойства Function.

Ответ 2

Это подход к созданию вызываемых объектов, которые правильно ссылаются на их члены-объекты и поддерживают правильное наследование, без возни с прототипами.

Просто:

class ExFunc extends Function {
  constructor() {
    super('...args', 'return this.__self__.__call__(...args)')
    var self = this.bind(this)
    this.__self__ = self
    return self
  }

  // Example '__call__' method.
  __call__(a, b, c) {
    return [a, b, c];
  }
}

Расширьте этот класс и добавьте метод __call__, подробнее ниже...

Объяснение в коде и комментариях:

// This is an approach to creating callable objects
// that correctly reference their own object and object members,
// without messing with prototypes.

// A Class that extends Function so we can create
// objects that also behave like functions, i.e. callable objects.
class ExFunc extends Function {
  constructor() {
    super('...args', 'return this.__self__.__call__(...args)');
    // Here we create a function dynamically using 'super', which calls
    // the 'Function' constructor which we are inheriting from. Our aim is to create
    // a 'Function' object that, when called, will pass the call along to an internal
    // method '__call__', to appear as though the object is callable. Our problem is
    // that the code inside our function can't find the '__call__' method, because it
    // has no reference to itself, the 'this' object we just created.
    // The 'this' reference inside a function is called its context. We need to give
    // our new 'Function' object a 'this' context of itself, so that it can access
    // the '__call__' method and any other properties/methods attached to it.
    // We can do this with 'bind':
    var self = this.bind(this);
    // We've wrapped our function object 'this' in a bound function object, that
    // provides a fixed context to the function, in this case itself.
    this.__self__ = self;
    // Now we have a new wrinkle, our function has a context of our 'this' object but
    // we are going to return the bound function from our constructor instead of the
    // original 'this', so that it is callable. But the bound function is a wrapper
    // around our original 'this', so anything we add to it won't be seen by the
    // code running inside our function. An easy fix is to add a reference to the
    // new 'this' stored in 'self' to the old 'this' as '__self__'. Now our functions
    // context can find the bound version of itself by following 'this.__self__'.
    self.person = 'Hank'
    return self;
  }
  
  // An example property to demonstrate member access.
  get venture() {
    return this.person;
  }
  
  // Override this method in subclasses of ExFunc to take whatever arguments
  // you want and perform whatever logic you like. It will be called whenever
  // you use the obj as a function.
  __call__(a, b, c) {
    return [this.venture, a, b, c];
  }
}

// A subclass of ExFunc with an overridden __call__ method.
class DaFunc extends ExFunc {
  constructor() {
    super()
    this.a = 'a1'
    this.b = 'b2'
    this.person = 'Dean'
  }

  ab() {
    return this.a + this.b
  }
  
  __call__(ans) {
    return [this.ab(), this.venture, ans];
  }
}

// Create objects from ExFunc and its subclass.
var callable1 = new ExFunc();
var callable2 = new DaFunc();

// Inheritance is correctly maintained.
console.log('\nInheritance maintained:');
console.log(callable2 instanceof Function);  // true
console.log(callable2 instanceof ExFunc);  // true
console.log(callable2 instanceof DaFunc);  // true

// Test ExFunc and its subclass objects by calling them like functions.
console.log('\nCallable objects:');
console.log( callable1(1, 2, 3) );  // [ 'Hank', 1, 2, 3 ]
console.log( callable2(42) );  // [ 'a1b2', Dean', 42 ]

// Test property and method access
console.log(callable2.a, callable2.b, callable2.ab())

Ответ 3

Вы можете обернуть экземпляр Smth в Proxy с помощью apply (и, возможно, construct):

class Smth extends Function {
  constructor (x) {
    super();
    return new Proxy(this, {
      apply: function(target, thisArg, argumentsList) {
        return x;
      }
    });
  }
}
new Smth(256)(); // 256

Ответ 4

Обновление:

К сожалению, это не совсем так, потому что теперь он возвращает объект функции вместо класса, поэтому, похоже, это невозможно сделать без изменения прототипа. Lame.


В основном проблема заключается в том, что невозможно установить значение this для конструктора Function. Единственный способ сделать это - использовать метод .bind, но это не очень удобно для класса.

Мы могли бы сделать это в базовом классе помощника, однако this не становится доступным только после первоначального вызова super, поэтому это немного сложно.

Рабочий пример:

'use strict';

class ClassFunction extends function() {
    const func = Function.apply(null, arguments);
    let bound;
    return function() {
        if (!bound) {
            bound = arguments[0];
            return;
        }
        return func.apply(bound, arguments);
    }
} {
    constructor(...args) {
        (super(...args))(this);
    }
}

class Smth extends ClassFunction {
    constructor(x) {
        super('return this.x');
        this.x = x;
    }
}

console.log((new Smth(90))());

Ответ 5

Я взял совет от Берги и завернул его в модуль NPM.

var CallableInstance = require('callable-instance');

class ExampleClass extends CallableInstance {
  constructor() {
    // CallableInstance accepts the name of the property to use as the callable
    // method.
    super('instanceMethod');
  }

  instanceMethod() {
    console.log("instanceMethod called!");
  }
}

var test = new ExampleClass();
// Invoke the method normally
test.instanceMethod();
// Call the instance itself, redirects to instanceMethod
test();
// The instance is actually a closure bound to itself and can be used like a
// normal function.
test.apply(null, [ 1, 2, 3 ]);

Ответ 6

Во-первых, я пришел к решению с arguments.callee, но это было ужасно. Я ожидал, что он перейдет в глобальный строгий режим, но похоже, что он работает даже там.

class Smth extends Function {
  constructor (x) {
    super('return arguments.callee.x');
    this.x = x;
  }
}

(new Smth(90))()

Это был плохой путь из-за использования arguments.callee, передачи кода в виде строки и принудительного его выполнения в нестрогом режиме. Но не появилась идея переопределить apply.

var global = (1,eval)("this");

class Smth extends Function {
  constructor(x) {
    super('return arguments.callee.apply(this, arguments)');
    this.x = x;
  }
  apply(me, [y]) {
    me = me !== global && me || this;
    return me.x + y;
  }
}

И тест, показывающий, что я могу запустить это как функцию по-разному:

var f = new Smth(100);

[
f instanceof Smth,
f(1),
f.call(f, 2),
f.apply(f, [3]),
f.call(null, 4),
f.apply(null, [5]),
Function.prototype.apply.call(f, f, [6]),
Function.prototype.apply.call(f, null, [7]),
f.bind(f)(8),
f.bind(null)(9),
(new Smth(200)).call(new Smth(300), 1),
(new Smth(200)).apply(new Smth(300), [2]),
isNaN(f.apply(window, [1])) === isNaN(f.call(window, 1)),
isNaN(f.apply(window, [1])) === isNaN(Function.prototype.apply.call(f, window, [1])),
] == "true,101,102,103,104,105,106,107,108,109,301,302,true,true"

Версия с

super('return arguments.callee.apply(arguments.callee, arguments)');

фактически содержит функциональность bind:

(new Smth(200)).call(new Smth(300), 1) === 201

Версия с

super('return arguments.callee.apply(this===(1,eval)("this") ? null : this, arguments)');
...
me = me || this;

делает call и apply на window несогласованным:

isNaN(f.apply(window, [1])) === isNaN(f.call(window, 1)),
isNaN(f.apply(window, [1])) === isNaN(Function.prototype.apply.call(f, window, [1])),

поэтому проверка должна быть перенесена в apply:

super('return arguments.callee.apply(this, arguments)');
...
me = me !== global && me || this;

Ответ 7

Это решение, которое я разработал, который удовлетворяет все мои потребности в расширении функций и хорошо меня обслужил. Преимущества этого метода:

  • При расширении ExtensibleFunction код является идиоматичным для расширения любого класса ES6 (нет, сбрасывает с помощью конструкторов или прокси-серверов).
  • Цепочка прототипа сохраняется во всех подклассах, а instanceof/.constructor возвращает ожидаемые значения.
  • .bind() .apply() и .call() все функции, как и ожидалось. Это делается путем переопределения этих методов для изменения контекста "внутренней" функции в отличие от экземпляра ExtensibleFunction (или его подкласса).
  • .bind() возвращает новый экземпляр конструктора функций (будь то ExtensibleFunction или подкласс). Он использует Object.assign() для обеспечения того, чтобы свойства, хранящиеся в связанной функции, соответствовали свойствам исходной функции.
  • Задержки соблюдаются, а функции стрелок продолжают поддерживать надлежащий контекст.
  • "Внутренняя" функция сохраняется через Symbol, которая может быть запутана модулями или IIFE (или любой другой общей методикой приватизации ссылок).

И без лишнего шума код:

// The Symbol that becomes the key to the "inner" function 
const EFN_KEY = Symbol('ExtensibleFunctionKey');

// Here it is, the `ExtensibleFunction`!!!
class ExtensibleFunction extends Function {
  // Just pass in your function. 
  constructor (fn) {
    // This essentially calls Function() making this function look like:
    // `function (EFN_KEY, ...args) { return this[EFN_KEY](...args); }`
    // `EFN_KEY` is passed in because this function will escape the closure
    super('EFN_KEY, ...args','return this[EFN_KEY](...args)');
    // Create a new function from `this` that binds to `this` as the context
    // and `EFN_KEY` as the first argument.
    let ret = Function.prototype.bind.apply(this, [this, EFN_KEY]);
    // For both the original and bound funcitons, we need to set the `[EFN_KEY]`
    // property to the "inner" function. This is done with a getter to avoid
    // potential overwrites/enumeration
    Object.defineProperty(this, EFN_KEY, {get: ()=>fn});
    Object.defineProperty(ret, EFN_KEY, {get: ()=>fn});
    // Return the bound function
    return ret;
  }

  // We'll make `bind()` work just like it does normally
  bind (...args) {
    // We don't want to bind `this` because `this` doesn't have the execution context
    // It the "inner" function that has the execution context.
    let fn = this[EFN_KEY].bind(...args);
    // Now we want to return a new instance of `this.constructor` with the newly bound
    // "inner" function. We also use `Object.assign` so the instance properties of `this`
    // are copied to the bound function.
    return Object.assign(new this.constructor(fn), this);
  }

  // Pretty much the same as `bind()`
  apply (...args) {
    // Self explanatory
    return this[EFN_KEY].apply(...args);
  }

  // Definitely the same as `apply()`
  call (...args) {
    return this[EFN_KEY].call(...args);
  }
}

/**
 * Below is just a bunch of code that tests many scenarios.
 * If you run this snippet and check your console (provided all ES6 features
 * and console.table are available in your browser [Chrome, Firefox?, Edge?])
 * you should get a fancy printout of the test results.
 */

// Just a couple constants so I don't have to type my strings out twice (or thrice).
const CONSTRUCTED_PROPERTY_VALUE = `Hi, I'm a property set during construction`;
const ADDITIONAL_PROPERTY_VALUE = `Hi, I'm a property added after construction`;

// Lets extend our `ExtensibleFunction` into an `ExtendedFunction`
class ExtendedFunction extends ExtensibleFunction {
  constructor (fn, ...args) {
    // Just use `super()` like any other class
    // You don't need to pass ...args here, but if you used them
    // in the super class, you might want to.
    super(fn, ...args);
    // Just use `this` like any other class. No more messing with fake return values!
    let [constructedPropertyValue, ...rest] = args;
    this.constructedProperty = constructedPropertyValue;
  }
}

// An instance of the extended function that can test both context and arguments
// It would work with arrow functions as well, but that would make testing `this` impossible.
// We pass in CONSTRUCTED_PROPERTY_VALUE just to prove that arguments can be passed
// into the constructor and used as normal
let fn = new ExtendedFunction(function (x) {
  // Add `this.y` to `x`
  // If either value isn't a number, coax it to one, else it `0`
  return (this.y>>0) + (x>>0)
}, CONSTRUCTED_PROPERTY_VALUE);

// Add an additional property outside of the constructor
// to see if it works as expected
fn.additionalProperty = ADDITIONAL_PROPERTY_VALUE;

// Queue up my tests in a handy array of functions
// All of these should return true if it works
let tests = [
  ()=> fn instanceof Function, // true
  ()=> fn instanceof ExtensibleFunction, // true
  ()=> fn instanceof ExtendedFunction, // true
  ()=> fn.bind() instanceof Function, // true
  ()=> fn.bind() instanceof ExtensibleFunction, // true
  ()=> fn.bind() instanceof ExtendedFunction, // true
  ()=> fn.constructedProperty == CONSTRUCTED_PROPERTY_VALUE, // true
  ()=> fn.additionalProperty == ADDITIONAL_PROPERTY_VALUE, // true
  ()=> fn.constructor == ExtendedFunction, // true
  ()=> fn.constructedProperty == fn.bind().constructedProperty, // true
  ()=> fn.additionalProperty == fn.bind().additionalProperty, // true
  ()=> fn() == 0, // true
  ()=> fn(10) == 10, // true
  ()=> fn.apply({y:10}, [10]) == 20, // true
  ()=> fn.call({y:10}, 20) == 30, // true
  ()=> fn.bind({y:30})(10) == 40, // true
];

// Turn the tests / results into a printable object
let table = tests.map((test)=>(
  {test: test+'', result: test()}
));

// Print the test and result in a fancy table in the console.
// F12 much?
console.table(table);

Ответ 8

Существует простое решение, которое использует функциональные возможности JavaScript: передайте "логику" как аргумент функции конструктору вашего класса, назначьте методы этого класса этой функции, затем верните эту функцию из конструктора в результате:

class Funk
{
    constructor (f)
    { let proto       = Funk.prototype;
      let methodNames = Object.getOwnPropertyNames (proto);
      methodNames.map (k => f[k] = this[k]);
      return f;
    }

    methodX () {return 3}
}

let myFunk  = new Funk (x => x + 1);
let two     = myFunk(1);         // == 2
let three   = myFunk.methodX();  // == 3

Выше было проверено на Node.js 8.

Недостатком приведенного выше примера является то, что он не поддерживает методы, унаследованные от суперкласса. Чтобы поддержать это, просто замените "Object. GetOwnPropertyNames (...)" на то, что возвращает также имена унаследованных методов. Как это сделать, я считаю, объясняется в другом вопросе-ответе на Stack Overflow:-). КСТАТИ. Было бы неплохо, если бы ES7 добавила метод для создания имен унаследованных методов;-).

Если вам нужно поддерживать унаследованные методы, одна возможность добавляет статический метод к указанному выше классу, который возвращает все имена наследованных и локальных методов. Затем вызовите это из конструктора. Если вы затем расширяете этот класс Funk, вы также получаете этот статический метод.