Javascript getter function from within function - javascript

I am trying to create my object through a function, but I am unable to figure out the syntax for the getter function.
var myObject =
{
0:123,
get a()
{
return this[0];
}
}
console.log("This works: " + myObject.a);
function test()
{
this[0] = 123;
// error
this.a = get function()
{
return this[0];
};
}
var myTest = new test();
console.log(myTest.a);
Within the test function, the assignment of the get function throws a missing semicolon error and if I remove the keyword "function", it says that get is not defined.
How can I assign a getter function to the current object within my function?

You could try something like this:
var myObject =
{
0:123,
get a()
{
return this[0];
}
}
console.log("This works: " + myObject.a);
function test()
{
this[0] = 123;
Object.defineProperties(this, {"a": { get: function () {
return this[0];
}}});
}
var myTest = new test();
console.log(myTest.a);

Maybe this will work for you :
function test()
{
this[0] = 123;
Object.defineProperty(this, "a", { get: function () { return this[0]; } });
}

Related

catch missing method call with javascript proxy

How can I get this code to work. I want to intercept all missing method calls on my function, and redirect them to a "catch all" kind of method on said function.
var foo=function(){
this.bar=function(){
return "found!";
}
this.not_found=function(){
return "method not found.";
}
}
var p = new Proxy(foo, {
get: function (target, prop) {
if (Object.keys(target).indexOf(prop) !== -1) {
// should call existing method.
//return target[prop]; <-- does not work.
}else{
// here i want to call "not_found() on foo() if prop doesnt exist
}
}
});
console.log(p.bar()); // should print out: found!;
console.log(p.foo()); // should print out: method not found;
thanks in advance!
foo is a function. As deepak said, if you create an object from it, it will work:
var Foo = function () {
this.bar = function () {
return "found!";
}
this.notFound = function () {
return "method not found.";
}
};
var p = new Proxy(new Foo, {
get: function (target, prop) {
if (Object.keys(target).indexOf(prop) !== -1) {
return target[prop];
} else {
return target['notFound'];
}
}
});
console.log(p.bar()); // prints: found!;
console.log(p.foo()); // prints: method not found;
Since Foo is acting like a constructor, I wrote it with a capital letter. Also, the convention is to use camel case for names. Took the liberty to change these.
A slightly cleaner version (using in):
var Foo = function () {
this.bar = function () {
return "found!";
}
this.notFound = function () {
return "method not found.";
}
};
var foo = new Foo();
var p = new Proxy(foo, {
get: function (target, prop) {
if (prop in target) {
return target[prop];
} else {
return target['notFound'];
}
}
});
console.log(p.bar()); // prints: found!;
console.log(p.foo()); // prints: method not found;

How to call parent function from descedant object? [duplicate]

This question already has answers here:
What is the 'new' keyword in JavaScript?
(17 answers)
Closed 3 years ago.
I have code like this:
function Thing() {
function foo() {
alert('1');
}
return { foo : foo }
}
window['myThings'] = {
bar : function() {
let t = new Thing();
t.foo = function() {
Thing.prototype.foo.call(this);
alert('2');
}
}
}
And have error: "Uncaught TypeError: Cannot read property 'call' of undefined". I want override object method with custom method, from which call parent method and then add some code. Where is my mistake?
P. S. Read article on the link from the comments and change code like this:
Thing = function () {
this.someVar = 1;
foo();
}
Thing.foo = function() {
alert('1');
}
window['myThings'] = {
bar : function() {
let t = new Thing();
t.foo();
}
}
And now i have an error: foo is not a function...
P. P. S. Change code like this:
function Thing() {};
Thing.prototype = function (arg) {
this.someVar = arg;
this.foo();
}
Thing.prototype.foo = function() {
alert('1');
}
window['myThings'] = {
bar : function() {
let t = new Thing(1);
t.foo();
}
}
myThings.bar();
And now: arg passed to constructor not stored in someVar or not readed from it...
Solution is here:
function Thing(arg) {
var private = 'private';
this.public = 'public';
this.init = function(arg) {
private = arg;
this.foo();
alert(private);
}
this.foo = function() {
alert('foo');
}
this.init(arg);
};
window['myThings'] = {
things : [],
bar : function() {
this.things[0] = new Thing('privateArg');
function AnotherThing(arg) {
Thing.call(this, arg);
var parentFoo = this.foo;
this.foo = function() {
// Call parent method
parentFoo();
// Run custom code
alert('foo foo');
}
}
// Parent init called with parent foo() method
this.things[1] = new AnotherThing(2);
// Customized foo() called
this.things[1].foo();
}
}
myThings.bar();

UnCaught TypeError - Nested objects in Javascript? Why is this not allowed? Object literal notation works

Playing around with some JS tests and I'm trying to instantiate some nested objects in my v namespace. As you'll see below, ClassA and ClassB work as expected. When I try and nest some objects under another property (myCustomProperty) I start running into issues! Could someone explain?
Below is the original code:
var v = (v) ? v : {};
v.someClassA = (function() {
this.hello = function() {
console.log("Class A Hello!");
}
});
v.someClassB = (function() {
this.hello = function() {
console.log("Class B Hello!");
}
});
// this all works!
var myClassA = new v.someClassA();
var myClassB = new v.someClassB();
v.myCustomProperty = (function() {
function someClassC() {
this.hello = function() {
console.log('C');
}
}
function someClassD() {
this.hello = function() {
console.log('D');
}
}
return {
someClassC: someClassC,
someClassD: someClassD
}
});
// Uncaught TypeError: v.myCustomProperty.someClassC is not a function! Why?
var myClassC = new v.myCustomProperty.someClassC();
var myClassD = new v.myCustomProperty.someClassD();
myClassA.hello();
myClassB.hello();
myClassC.hello();
myClassD.hello();
If I change my declaration of v.myCustomProperty to use object literal notation, then it ALL WORKS! :
v.myCustomProperty = {
someClassC: function() {
this.hello = function() {
console.log('C');
}
},
someClassD: function() {
this.hello = function() {
console.log('D');
}
}
}
I guess my question really is how would I make this work using the notation in my original snippet? Possible? Horrible practice to do it that way?
Thanks!
v.myCustomProperty is a function that returns an object. You have to call the function first:
new (v.myCustomProperty().someClassC)();
// ^^
Otherwise, v.myCustomProperty.someClassC() tries to access the property someClassC of the function, and we all know (hopefully) that functions don't have such a property.
Or maybe you intended to execute the function immediately and assign the object to myCustomProperty?
v.myCustomProperty = (function() {
// ...
}()); // <- call function

JavaScript - why must we return a function from a self-invoking function?

This code has a runtime error:
var person = (function(){
var Person = {
init: function() {
},
};
return new Person();
/*return function(){
new Person();
}*/
})();
console.log(person);
it says I have to return a function instead of a plain Object.
Why is that I can't return an object from the self-invoking/anonymous outer function? Why must I return a function?
likewise, this altered code also gives me a similar error:
var person = function(){
var Person = {
init: function() {
},
};
return new Person();
/*return function(){
new Person();
}*/
};
console.log(person());
Why is that I can't return an object from the self-invoking/anonymous outer function?
You can return an object, that is not what's wrong with your code.
The problem with your code is that Person is an object, not a function. Calling new Person() is invalid.
var person = (function () {
return {
name: 'bob'
};
}());
console.log(person.name);
The problem here is that you have declared Person as an object, and you can't use new Person() with an object. To create a "class" in ES5 you create a function instead.
var person = (function(){
var Person = function() {
this.init = function() {
console.log('Initing!')
}
};
return new Person();
})();
console.log(person);
http://jsfiddle.net/758zL8v3/
The alternative is the following Object constructor:
var person = function(){
var Person = function(){
this.init = function() {
};
};
return new Person();
};
You can read more about Object Oriented programming here.
Why must I return a function?
Because the new operator creates an instance of a Javascript Object. And to create it, it needs a constructor function. And that is that function you're asking about.
It's almost like calling a typical function
function add() {
return 1 + 1;
}
add();
// 2
but when you call it with the new operator, you create a new instance of this function object (functions are objects too, in Javascript).
function myAdder() {
this.a = 1;
this.b = 1;
this.add = function () {
return this.a + this.b;
};
return this;
}
myObject = new myAdder();
myObject.b = 2;
myObject.add();
// 3
And the object notation of myAdder would be:
function myAdder() {
return {
a: 1,
b: 1,
add: function () {
return this.a + this.b;
}
};
}

JavaScript, inherited function is printed out as undefined

I am wondering why JSON.stringify(this.Master.Func) returns 'undefined' instead of function() { ... }.
Function itself executes by adding ().
JSfiddle: http://jsfiddle.net/t4ngY/
CODE
var $ = {}; // some global
var Master =
{
property: 'Property',
Func: function()
{
console.log('I am Func inside Master');
},
PassToGlobal: function()
{
$.master = this;
}
};
Master.PassToGlobal();
var Slave =
{
Master: $.master,
ShowFunc: function()
{
console.log(JSON.stringify(this.Master.Func)); //returns undef
this.Master.Func(); //prints `I am Func inside Master`
}
}
Slave.ShowFunc();
if you want see function text you can simply call toString method like this
console.log(this.Master.Func.toString());

Categories

Resources