Function with `return` - javascript

Looking at the foo function on Bar.prototype:
Bar.prototype.foo = function() {
return console.log("Foo");
};
What's the difference between
Bar = function(name) {
...
this.foo();
};
and
Bar= function(name) {
...
return this.foo(); // note the 'return'
};

The first Bar function returns undefined, which is the default return value of a function in javascript.
The second Bar function returns the result of the this.foo function, which in turn appears to return the result of console.log, which again is undefined.
So they both return undefined, but they do take a different path to get that undefined value.

Related

Javascript getter

Given the following code are foo, bar and baz all effectively the same? What if any is the advantage of using the get keyword?
var getValue = function () {
return 'value';
}
var foo = {
value: getValue(),
};
var bar = {
get value() {
return getValue();
},
};
var baz = {
get value() {
return 'value';
},
};
console.log('foo.value', foo.value); // foo.value value
console.log('bar.value', bar.value); // bar.value value
console.log('baz.value', baz.value); // baz.value value
Given the following code are foo, bar and baz all effectively the same?
No, not at all.
foo will have a value property that will be the result of calling getValue when foo was created, and will not call getValue later.
bar will have a value property that, when accessed like bar.value, calls getValue and returns its return value.
baz will have a value property with the explicit value 'value'.
The differences are:
Whether getValue is called
When getValue is called
This is more obvious with some logging and with a slightly updated version of getValue:
var getValue = function () {
var value = Math.floor(Math.random() * 1000);
console.log("getValue called, returning " + value);
return value;
}
console.log("Creating foo");
var foo = {
value: getValue(),
};
console.log("Creating bar");
var bar = {
get value() {
return getValue();
},
};
console.log("Creating baz");
var baz = {
get value() {
return 42;
},
};
console.log("Calling foo");
console.log('foo.value', foo.value);
console.log("Calling bar");
console.log('bar.value', bar.value);
console.log("Calling baz");
console.log('baz.value', baz.value);
.as-console-wrapper {
max-height: 100% !important;;
}
The advantage (and disadvantage) to a getter is you can execute logic (such as calling getValue) in response to what looks like a simple property lookup (bar.value, rather than bar.value() or bar.getValue()).

get function execution context

I have a function foo:
function foo() {
return 'foo';
}
While foo got executed is there a way to know if foo was called inside object declaration ? I want to distinguish these two cases:
var bar = {
prop1: foo()
}
var var1 = foo();
Here's one approach demonstrating the suggestions in the comments and assuming you'd rather call bar.prop1 instead of bar.prop1().
function foo (ctx) {
console.log(ctx == window)
return 'foo'
}
class Bar {
get prop1() {
return foo(this)
}
}
var var1 = foo(this);
var bar = new Bar();
bar.prop1;

Some strange when using Promise in JavaScript

I have a function that returns a promise object. This is my code
var foo = function(){
// doSomething() is a promise object
return doSomething().then(() => {
Promise.resolve('Hello');
});
};
foo().then((res) => {
console.log(res);
// res = undefined but not "Hello"
});
I thought function foo would return the promise object and I would get the string "Hello". But I get undefined. Why?
You're missing a return before Promise.resolve, so it should be
var foo = function(){
return doSomething().then(() => {
return Promise.resolve('Hello');
^^^^^^
});
};
However, actually you don't need that at all, and could just return the string Hello.
var foo = function(){
return doSomething().then(() => {
return 'Hello';
});
};
You could make it even simpler by using the concise body form of arrow function, leaving off the {}.
var foo = function(){
return doSomething().then(() => 'Hello');
};

Why should fix 'this' when return a function?

I read the piece of code in a book,
Function.prototype.before = function(beforefn){
var _self = this;
return function(){
beforefn.apply(this,arguments);
return _self.apply(this,arguments);
}
}
when execute
beforefn.apply(this,arguments);andreturn _self.apply(this,arguments);,I think even without fix 'this' it will get the same result.
function test(){
return function(){
alert(this.foo);
}
}
var o1 = {
foo:"foo",
test:test(),
}
o1.test(); //alert foo
So what is the purpose to fix this of the author?
P.S This is the first time ask question in StackOverflow,forgive my bad English.Thanks
Thanks for noticing my question! I would rewrite like this:
Function.prototype.before = function(beforefn){
var _self = this;
return function(){
beforefn(arguments);
return arguments.callee;
}
}
.apply(this, …) doesn't fix the thisArg - in contrast, it even makes it dynamic, using the current dynamic this from the returned function. Have a look at how well it works:
function test(){
alert(this.foo);
}
var o1 = {
foo: "bar",
test: test.before(function() { console.log(this); })
};
o1.test(); // logs o1, alerts "bar"
o1.test.call({}); // logs the empty object, alerts undefined
You'd only fix the this argument of _self if you didn't pass the current this, as in
Function.prototype.before = function(beforefn){
var fn = this;
return function() {
beforefn.apply(null, arguments);
return fn.apply(null, arguments);
}
}
where o1.test() would not work any more. Of course, apply is still necessary to pass a variable amount of arguments to the function.

Chrome Web inspector shows unusual symbol when calling prototype method in console

So I have this function called "createGameObjectConstructor" which takes a function and a prototype adds the prototype and a method to the function then returns the function.It can be used like this
Monster = createGameObjectConstructor(function () {
this.evilness = 9001;
}, {
eatHuman:function () {
console.log('human consumed');
}, type:'scary'
});
and "createGameObjectConstructor" looks like this
createGameObjectConstructor = (function () {
var recent = function () { //every actual object constructor will share this method
return (instance.length> 0) ? instance[instance.length - 1] :null;
};
return function (constructor, prototype) { //createGameObjectConstructor
var instanceArray = new Array();
constructor.prototype = prototype;
return function (){ //actual object's constructor
var instance = new constructor();
instance.constructor = constructor;
instanceArray.push();
return instance;
};
f.recent = recent;
return f;
}
}());
But when I call Monster().eatHuman(); in Chrome's console it returns the function undefined but with a weird arrow next to it, is this because my bizarre coding somehow led it too eval the code or something?
here's a fiddle http://jsfiddle.net/UZmL9/
This just means the return value of the function is undefined.
All JavaScript functions return undefined by default if no explicit return statement is found.
function foo(){
console.log("Hi");
}
foo(); // you will get the same 'undefined'
But
function foo(){
console.log("Hi");
return 5;
}
foo(); // you will get 5 with that arrow

Categories