Javascript bind Function Implementation - javascript

I want to Create Polyfill for bind function of javascript for the browser which does not support bind function. Anyone, please tell how bind function is implemented in javascript.

In its simplest form, bind is just a wrapper for apply:
function bind(fn, thisObj) {
return function() {
return fn.apply(thisObj, arguments);
}
}

Implemented the basic functionality of bind by using apply.
I called this method myBind, added it to the function prototype so that it's accessible by any function:
Function Implementation
Function.prototype.myBind = function() {
const callerFunction = this;
const [thisContext, ...args] = arguments;
return function() {
return callerFunction.apply(thisContext, args);
}
}
Usage:
Can be used as a native bind function taking in the context and arguments.
function testMyBind(favColor) {
console.log(this.name, favColor); // Test, pink
}
const user = {
name: 'Test'
}
const bindedFunction = testMyBind.myBind(user, 'pink');
bindedFunction();

To keep things simple, while using the modern JavaScript:
Function.prototype.bind = function () {
return () => this.call(...arguments);
};
That's all there is to it.

Implemented the basic functionality using apply. Both bind function and bound function can accept arguments.
Function.prototype.bindPolyfill = function (obj, ...args) {
const func = this;
return function (...newArgs) {
return func.apply(obj, args.concat(newArgs));
};
};
Usage:
const employee = { id: '2'};
const getEmployee = function(name, dept){
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales');

Function.prototype.bindPolyfill = function (newThis, ...args) {
return (...newArgs) => {
return this.apply(newThis, [...args, ...newArgs]);
};
};
// Usage
const employee = { id: '2' };
const getEmployee = function (name, dept) {
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales'); // 2 test Sales

Function.prototype.customBind = function(ctx, ...args) {
const fn = this;
return function() {
return fn.apply(ctx, args);
}
}
A simple solution

Related

How do I get the arguments passed to a function that is a property of an object?

I have an object that has a property which is a function:
Example:
const obj = {func: function() {console.log('I am a function in an object')}};
When I call this function, I would call it by obj.func(). If I wanted to pass more arguments to this function, how can I access them? I've tried:
const obj = {
func: function() {
const args = [...arguments];
console.log(args);
}
}
so when I call obj.func(arg1, arg2), I expect it to log what arg1 and arg2 is but this call returns the obj as the single argument. I have not found any other answer about this. BTW, I'm new to javascript.
Just use a loop and arguments to straight away access your function arguments. Here's an alteration to your function:
const obj = {
func: function() {
for (var iteration=0; iteration<arguments.length; iteration++)
console.log(arguments[iteration]);
}
}
Just paste it as a value...
const obj = {
func: function() {
const args = [...arguments];
console.log(args);
}
}
obj.func("value1","value2")
or like this
const obj = {
func: function(arg1,arg2) {
const args = [arg1,arg2];
console.log(args);
}
}
obj.func("value1","value2")
const obj = {
func: function() {
const args = [arguments[0],arguments[1]];
console.log(args);
}
}
obj.func("value1","value2")
An even easier option that does not need the arguments variable would be the following:
const obj = {
func: (...args) => {
console.log(args);
}
};
obj.func("value1", "value2");

function object with public static properties

So I know I can add public properties to functions directly like this.
const print = function (string) {
console.log(string);
};
print.uppercase = function (string) {
print(string.toUpperCase());
};
print("apple"); // apple
print.uppercase("apple"); // APPLE
But I always follow this pattern when I make objects.
const object = function () {
let field;
const getField = function () {
return field;
};
const setField = function (_field) {
field = _field;
};
return Object.freeze({
getField,
setField
});
};
Is it possible to make function objects with public properties while sticking to this pattern? Without using this?
const factory = function () {
const generic = function () {};
const specific = function () {};
return Object.freeze({
// DO SOMETHING HERE SO THAT
});
};
// factory() invokes the generic function, and
// factory.specific() invokes the specific function
I think you are looking for
generic.specific = specific;
Object.freeze(generic);
return generic;
or for short,
return Object.freeze(Object.assign(generic, {
specific,
}));

How to access constructor function from object by using this

In this example. I need to update friends list from object function.
var MyClass = function () {
this.friends = [];
this.runtime = {
add: function (name) {
this.friends.push(name);
}
}
};
MyClass.prototype.AddFriend = function (name) {
this.runtime.add(name);
};
MyClass.prototype.GetFriends = function () {
return this.friends;
};
How it's possible?
You could also use the bind() method:
var MyClass = function () {
this.friends = [];
this.runtime = {
add: function (name) {
this.friends.push(name);
}.bind(this)
}
};
MyClass.prototype.AddFriend = function (name) {
this.runtime.add(name);
};
MyClass.prototype.GetFriends = function () {
return this.friends;
};
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Like I said in the comments, it makes much more sense to use this.friends.push(name), but if you really have to use that odd runtime function, then you need to save a copy of this to a new variable:
var MyClass = function () {
var _this = this;
this.friends = [];
this.runtime = {
add: function (name) {
_this.friends.push(name);
}
}
};
DEMO

Rewiring a JavaScript function

Let's say I have a function named fna() that does a simple thing such as:
var fna = function(ar) {
console.log("argument: ", ar);
return "return value is argument too: " + ar;
}
fna() is coded by some other developer and I can't access to it. He didn't bother casting any events and when it is called, I have to be aware of it. Hopefully, his method is accessible by window.fna().
I want some additional code to be executed. Let's say, add this console.log
var fna = function(ar) {
console.log("Hola, I am some additional stuff being rewired");
console.log("argument:", ar);
return "return value is argument too: " + ar;
}
And I want this to be executed even when called from fnb() by some other part of the code.
var fnb = function() {
return fna("Bonjour, I am fnb and I call fna");
}
Here is a way I found, using the utils.rewire() method. utils is just some utility belt, and it could be added to your favorite framework as a plugin. Unfortunately, it only works on Firefox.
var utils = utils || {};
// Let's rewire a function. i.e. My.super.method()
utils.rewire = function(functionFullName, callback) {
var rewired = window[functionFullName];
console.log("%s() is being rewired", functionFullName)
window[functionFullName] = function() {
callback();
return rewired.apply(this, arguments);
}
}
Use it like this.
utils.rewire("fna",function(){
console.log("Hola, I am some additional stuffs being rewired");
});
This seems to work such as shown in this jsbin, but (and here is my question:) How do I rewire obja.fna()?
var obja = {
fna = function(ar) {
console.log("argument:", ar);
return "return value is argument too: " + ar;
}
};
I cannot make it work to rewire the some.object.method() method.
Extra bonus question: Is there a more cleaner way to do this? Out-of-the-box clean concise and magic library?
Refactor rewire into a rewireMethod function which acts on any given object:
var utils = utils || {};
utils.rewireMethod = function (obj, functionName, prefunc) {
var original = obj[functionName];
obj[functionName] = function () {
prefunc();
return original.apply(this, arguments);
};
};
Note that rewire can now be written as:
utils.rewire = function (functionName, prefunc) {
utils.rewireMethod(window, functionName, prefunc);
};
Then you just call it as:
utils.rewireMethod(obja, "fna", function () {
console.log("Hola, I am some additional stuff being rewired");
});
Note that nothing special is required if you have a method like window.ideeli.Search.init(). In that case, the object is window.ideeli.Search, and the method name is init:
utils.rewireMethod(window.ideeli.Search, "init", function () {
console.log("Oh yeah, nested objects.");
});
Add a parameter to rewire that is the object containing the function. If it's a global function, pass in window.
var utils = utils || {};
// let's rewire a function. i.e. My.super.method()
utils.rewire = function(object, functionName, callback) {
var rewired = object[functionName];
console.log("%s() is being rewired", functionName)
object[functionName] = function() {
callback();
return rewired.apply(this, arguments);
}
}
utils.rewire(some.object, "method", function(){} );
You can simply use a closure to create a generic hook function that allows you to specify another function to be called immediately before or after the original function:
function hookFunction(fn, preFn, postFn) {
function hook() {
var retVal;
if (preFn) {
preFn.apply(this, arguments);
}
retVal = fn.apply(this, arguments);
if (postFn) {
postFn.apply(this, arguments);
}
return retVal;
}
return hook;
}
So, for any function that you want to hook, you just call hookFunction and pass it the function you want to hook and then an optional pre and post function or yours. The pre and post function are passed the same arguments that the original function was.
So, if your original function was this:
var fna = function(ar) {
console.log("argument:",ar);
return "return value is argument too:"+ar;
}
And, you want something to happen every time that function is called right before it's called, you would do this:
fna = hookFunction(fna, function() {
console.log("Hola, I am some additional stuff being rewired right before");
});
or if you wanted it to happen right after the original was called, you could do it like this:
fna = hookFunction(fna, null, function() {
console.log("Hola, I am some additional stuff being rewired right after");
});
Working demo: http://jsfiddle.net/jfriend00/DMgn6/
This can be used with methods on objects and arbitrary nesting levels of objects and methods.
var myObj = function(msg) {
this.greeting = msg;
};
myObj.prototype = {
test: function(a) {
log("myObj.test: " + this.greeting);
}
}
var x = new myObj("hello");
x.test = hookFunction(x.test, mypreFunc2, myPostFunc2);
x.test("hello");
Based on Claudiu's answer, which seems to be the most appreciated way, here is a solution using a for loop and proxying the context... But still, I find this ugly.
var utils = utils || {};
// Let's rewire a function. i.e. My.super.method()
utils.rewire = function(method, callback) {
var obj = window;
var original = function() {};
var tree = method.split(".");
var fun = tree.pop();
console.log(tree);
// Parse through the hierarchy
for (var i = 0; i < tree.length; i++) {
obj = obj[tree[i]];
}
if(typeof(obj[fun]) === "function") {
original = obj[fun];
}
var cb = callback.bind(obj);
obj[fun] = function(ar) {
cb();
return original.apply(this, arguments);
}
}
Well, this looks strange. Consider this
function wrap(fn, wrapper) {
return function() {
var a = arguments;
return wrapper(function() { return fn.apply(this, a) })
}
}
Example:
function foo(a, b) {
console.log([a, b])
return a + b
}
bar = wrap(foo, function(original) {
console.log("hi")
var ret = original()
console.log("there")
return ret
})
console.log(bar(11,22))
Result:
hi
[11, 22]
there
33
To wrap object methods, just bind them:
obj = {
x: 111,
foo: function(a, b) {
console.log([a, b, this.x])
}
}
bar = wrap(obj.foo.bind(obj), function(fn) {
console.log("hi")
return fn()
})

Asynchronous constructor

How can I best handle a situation like the following?
I have a constructor that takes a while to complete.
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
var oxygen = new Element('oxygen');
console.log(oxygen.nucleus); // Returns {}, because load_nucleus hasn't finished.
I see three options, each of which seem out of the ordinary.
One, add a callback to the constructor.
var Element = function Element(name, fn){
this.name = name;
this.nucleus = {};
this.load_nucleus(name, function(){
fn(); // Now continue.
});
}
Element.prototype.load_nucleus(name, fn){
fs.readFile(name+'.json', function(err, data) {
this.nucleus = JSON.parse(data);
fn();
});
}
var oxygen = new Element('oxygen', function(){
console.log(oxygen.nucleus);
});
Two, use EventEmitter to emit a 'loaded' event.
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
Element.prototype.load_nucleus(name){
var self = this;
fs.readFile(name+'.json', function(err, data) {
self.nucleus = JSON.parse(data);
self.emit('loaded');
});
}
util.inherits(Element, events.EventEmitter);
var oxygen = new Element('oxygen');
oxygen.once('loaded', function(){
console.log(this.nucleus);
});
Or three, block the constructor.
var Element = function Element(name){
this.name = name;
this.nucleus = {};
this.load_nucleus(name); // This might take a second.
}
Element.prototype.load_nucleus(name, fn){
this.nucleus = JSON.parse(fs.readFileSync(name+'.json'));
}
var oxygen = new Element('oxygen');
console.log(oxygen.nucleus)
But I haven't seen any of this done before.
What other options do I have?
Update 2:
Here is an updated example using an asynchronous factory method. N.B. this requires Node 8 or Babel if run in a browser.
class Element {
constructor(nucleus){
this.nucleus = nucleus;
}
static async createElement(){
const nucleus = await this.loadNucleus();
return new Element(nucleus);
}
static async loadNucleus(){
// do something async here and return it
return 10;
}
}
async function main(){
const element = await Element.createElement();
// use your element
}
main();
Update:
The code below got upvoted a couple of times. However I find this approach using a static method much better:
https://stackoverflow.com/a/24686979/2124586
ES6 version using promises
class Element{
constructor(){
this.some_property = 5;
this.nucleus;
return new Promise((resolve) => {
this.load_nucleus().then((nucleus) => {
this.nucleus = nucleus;
resolve(this);
});
});
}
load_nucleus(){
return new Promise((resolve) => {
setTimeout(() => resolve(10), 1000)
});
}
}
//Usage
new Element().then(function(instance){
// do stuff with your instance
});
Given the necessity to avoid blocking in Node, the use of events or callbacks isn't so strange(1).
With a slight edit of Two, you could merge it with One:
var Element = function Element(name, fn){
this.name = name;
this.nucleus = {};
if (fn) this.on('loaded', fn);
this.load_nucleus(name); // This might take a second.
}
...
Though, like the fs.readFile in your example, the core Node APIs (at least) often follow the pattern of static functions that expose the instance when the data is ready:
var Element = function Element(name, nucleus) {
this.name = name;
this.nucleus = nucleus;
};
Element.create = function (name, fn) {
fs.readFile(name+'.json', function(err, data) {
var nucleus = err ? null : JSON.parse(data);
fn(err, new Element(name, nucleus));
});
};
Element.create('oxygen', function (err, elem) {
if (!err) {
console.log(elem.name, elem.nucleus);
}
});
(1) It shouldn't take very long to read a JSON file. If it is, perhaps a change in storage system is in order for the data.
I have developed an async constructor:
function Myclass(){
return (async () => {
... code here ...
return this;
})();
}
(async function() {
let s=await new Myclass();
console.log("s",s)
})();
async returns a promise
arrow functions pass 'this' as is
it is possible to return something else when doing new (you still get a new empty object in this variable. if you call the function without new. you get the original this. like maybe window or global or its holding object).
it is possible to return the return value of called async function using await.
to use await in normal code, need to wrap the calls with an async anonymous function, that is called instantly. (the called function returns promise and code continues)
my 1st iteration was:
maybe just add a callback
call an anonymous async function,
then call the callback.
function Myclass(cb){
var asynccode=(async () => {
await this.something1();
console.log(this.result)
})();
if(cb)
asynccode.then(cb.bind(this))
}
my 2nd iteration was:
let's try with a promise instead of a callback.
I thought to myself: strange a promise returning a promise, and it worked. .. so the next version is just a promise.
function Myclass(){
this.result=false;
var asynccode=(async () => {
await new Promise (resolve => setTimeout (()=>{this.result="ok";resolve()}, 1000))
console.log(this.result)
return this;
})();
return asynccode;
}
(async function() {
let s=await new Myclass();
console.log("s",s)
})();
callback-based for old javascript
function Myclass(cb){
var that=this;
var cb_wrap=function(data){that.data=data;cb(that)}
getdata(cb_wrap)
}
new Myclass(function(s){
});
One thing you could do is preload all the nuclei (maybe inefficient; I don't know how much data it is). The other, which I would recommend if preloading is not an option, would involve a callback with a cache to save loaded nuclei. Here is that approach:
Element.nuclei = {};
Element.prototype.load_nucleus = function(name, fn){
if ( name in Element.nuclei ) {
this.nucleus = Element.nuclei[name];
return fn();
}
fs.readFile(name+'.json', function(err, data) {
this.nucleus = Element.nuclei[name] = JSON.parse(data);
fn();
});
}
This is a bad code design.
The main problem is in the callback your instance it's not still execute the "return", this is what I mean
var MyClass = function(cb) {
doAsync(function(err) {
cb(err)
}
return {
method1: function() { },
method2: function() { }
}
}
var _my = new MyClass(function(err) {
console.log('instance', _my) // < _my is still undefined
// _my.method1() can't run any methods from _my instance
})
_my.method1() // < it run the function, but it's not yet inited
So, the good code design is to explicitly call the "init" method (or in your case "load_nucleus") after instanced the class
var MyClass = function() {
return {
init: function(cb) {
doAsync(function(err) {
cb(err)
}
},
method1: function() { },
method2: function() { }
}
}
var _my = new MyClass()
_my.init(function(err) {
if(err) {
console.error('init error', err)
return
}
console.log('inited')
// _my.method1()
})
I extract out the async portions into a fluent method. By convention I call them together.
class FooBar {
constructor() {
this.foo = "foo";
}
async create() {
this.bar = await bar();
return this;
}
}
async function bar() {
return "bar";
}
async function main() {
const foobar = await new FooBar().create(); // two-part constructor
console.log(foobar.foo, foobar.bar);
}
main(); // foo bar
I tried a static factory approach wrapping new FooBar(), e.g. FooBar.create(), but it didn't play well with inheritance. If you extend FooBar into FooBarChild, FooBarChild.create() will still return a FooBar. Whereas with my approach new FooBarChild().create() will return a FooBarChild and it's easy to setup an inheritance chain with create().
You can run constructor function with async functions synchronously via nsynjs. Here is an example to illustrate:
index.js (main app logic):
var nsynjs = require('nsynjs');
var modules = {
MyObject: require('./MyObject')
};
function synchronousApp(modules) {
try {
var myObjectInstance1 = new modules.MyObject('data1.json');
var myObjectInstance2 = new modules.MyObject('data2.json');
console.log(myObjectInstance1.getData());
console.log(myObjectInstance2.getData());
}
catch (e) {
console.log("Error",e);
}
}
nsynjs.run(synchronousApp,null,modules,function () {
console.log('done');
});
MyObject.js (class definition with slow constructor):
var nsynjs = require('nsynjs');
var synchronousCode = function (wrappers) {
var config;
// constructor of MyObject
var MyObject = function(fileName) {
this.data = JSON.parse(wrappers.readFile(nsynjsCtx, fileName).data);
};
MyObject.prototype.getData = function () {
return this.data;
};
return MyObject;
};
var wrappers = require('./wrappers');
nsynjs.run(synchronousCode,{},wrappers,function (m) {
module.exports = m;
});
wrappers.js (nsynjs-aware wrapper around slow functions with callbacks):
var fs=require('fs');
exports.readFile = function (ctx,name) {
var res={};
fs.readFile( name, "utf8", function( error , configText ){
if( error ) res.error = error;
res.data = configText;
ctx.resume(error);
} );
return res;
};
exports.readFile.nsynjsHasCallback = true;
Full set of files for this example could be found here: https://github.com/amaksr/nsynjs/tree/master/examples/node-async-constructor

Categories

Resources