How to call method of another function without prototyping [duplicate] - javascript

This question already has answers here:
Javascript Class Inheritance For Functions
(2 answers)
Call parent method in JavaScript class but stll have access to prototype methods inside object instance?
(5 answers)
Closed 5 years ago.
This is surely trivial question, but I am little confused with JavaScript. I want to call method inside another function. I have spent some time to handle this and all I have got so far is the second piece of code. I would like to know, if there is any similar solution as noted in comment.
function Student() {
this.greeting = function() {
alert('Hi! I\'m student.');
};
};
function Teacher() {
Student.call(this)
this.greeting = function() {
Student.??? // here I want something like "inherited", or call Student.greeting()
alert('and I like apples');
};
};
I want to be sure, there is no another option like prototyping:
function Student() {
};
Student.prototype.greeting = function() {
alert('Hi! I\'m student.');
};
function Teacher() {
Student.call(this);
this.greeting = function() {
Student.prototype.greeting();
alert('and I like apples');
};
};
Thanx

Student is a function, in your case it is also a constructor.
To call "Student" you need to save object returned by call of constructor-function Student
function Teacher() {
var stdnt = new Student()
this.greeting = function() {
stdnt.greeting()
alert('and I like apples');
};
};
Also, in your code Student.call(this) is equivalent to just function call Student() - without creation of new object
Upd2. This call of stdnt from inner function called "closure"

Related

JavaScript field access from anonymous function [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
how can I access a fiel from within an anonymous function inside a method?
like in this example:
class Something {
constructor (){
this.gax = “gax”;
}
doSomething(){
(function () {
console.log(this.gax);
}());
}
}
new Something().doSomething();
this will result in an error that "this" is undefined.
thank you very much in advance, I could not find an answer in the web after searching for hours.
best,
lev
In your anonymous function, this is bound to the function; it no longer refers to the class.
Use an arrow function instead, which doesn't have it's own this binding.
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(() => {
console.log(this.gax);
})();
}
}
new Something().doSomething();
Alternatively, you could use something like .call(), .apply(), or .bind():
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function() {
console.log(this.gax);
}).call(this);
}
}
new Something().doSomething();
class Something {
constructor (){
this.gax = "gax";
}
doSomething(){
(function () {
console.log(this.gax);
}).apply(this);
}
}
new Something().doSomething();
You can use apply method. The apply() method calls a function with a given this value

Javascript Objects Clarification [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 4 years ago.
am a beginner learning javascript and was playing around with Objects and am wondering why this code is throwing an error.
var a = {
greeting: "Hello",
greet: this.greeting + "John"
}
console.log(a.greet);
While it's been clarified why your code throws an error, I wanted to explain how you could have it instead.
Javascript makes no difference between ordinary functions and constructors, to a class is just a call to new function with any function in front of it.
Therefore, a way the object can reference itself is by using a function body as its definition:
const AClass = function () {
this.greeting = 'Hello'
this.greet = this.greeting + ' John'
}
const a = new AClass()
console.log(a.greet)
Shorthand since you aren't going to create more than one AClass object (at least in your example):
const a = new function () {
this.greeting = 'Hello'
this.greet = this.greeting + ' John'
}()
console.log(a.greet)
Yours doesn't work because of the problems described in the comments.
I'm guessing that you want something like this:
var a = {
greeting: "Hello",
greet: function() {return this.greeting + " John"}
}
console.log(a.greet());
Or like this:
var a = (() => {
var greeting = "Hello"
return {
greeting,
greet: greeting + ' John'
}
})()
console.log(a.greet);
The first one makes greet a function, which means that it will respond to later changes in greeting. The second one creates an object based on the greeting value. But you have to use a local variable for the reference, since your this at the time of construction is not the new object but some outer scope, possibly something like window.
This question you have is explained here: How Do I reference objects proerty at creation
In order to do what you want you can use an object getter.
var b = {
greeting: "Hello",
get greet() { //this a getter that accesses greeting
return this.greeting + " John";
}
}
console.log(b.greet);

Javascript function Inheritance [duplicate]

This question already has answers here:
JavaScript inheritance: Object.create vs new
(5 answers)
Closed 7 years ago.
I know this question was answered so many times, but I am so confused about how to inherit (yes, inherit....again) two Javascript functions.
Assumed that I have a class called 'Base' which is the one that I want to inherit;
function Base(model)
{
var self=this;
self._model=model;
return self;
}
Base.prototype.modelName= function()
{
return self._model.Name;
};
Then I create a new class call Foo.
function Foo()
{
var self=this;
self.hello=function()
{
return 'Hello World';
}
return self;
}
What code should I add to the Foo class to be able to do something like this?
var myModel={type:1, name:'My Model'};
var myObj=new Foo(myModel);
var result= MyObj.modelName();
I know I should use the object.create() method, but I cannot understand exactly how! :(
Thank you guys, and again sorry for this silly question.....I am really struggling with this basic concept here!!!!
JavaScript uses prototypal inheritance. To inherit from Base class, use like
Foo.prototype = new Base();
But you can't pass parameters into Foo. You need to move model save logic to Foo.
NOTE: Don't return the created object from constructor functions. By default, created object is returned.
EDITED
function Base() {
}
Base.prototype.modelName = function () {
return self._model.Name;
};
function Foo(model)
{
this._model = model
this.hello = function () {
return 'Hello World';
}
}
Foo.prototype = new Base();

The 'this' keyword in a function [duplicate]

This question already has answers here:
How does "this" keyword work within a function?
(7 answers)
Closed 8 years ago.
I have a function in JavaScript:
function main() {
console.log(this);
}
How come this logs Document? Surely it should log function main?
If not, then how do I declare a variable within main to be accessed by the rest of the code as main.varName?
Thank you!
Hey you can do something like this.
But then this would look something like a class object.
<script>
function main() {
this.testVar = "124";
}
var testMain = new main();
alert(testMain.testVar);
</script>
The alternative is that you just create a normal global variable.
The way i am taking the code is a more class object way.
Hope i could help :)
The this keyword references the context of the function, not the function itself.
When you call a function as a method of an object, then this references the object, otherwise the context is the global context (document).
Example:
var o = {
name: 'myObject',
fn: function(){ alert(this.name); }
};
o.fn(); // alerts "myObject"
As a function is also an object, you can add properties to it:
function main() {
}
main.varName = 42;
alert(main.varName); // shows "42"
However, this is not a regular use of functions and objects. Normally main would be a plain object rather than a function if you want to access main.varName.
Also, check out the module pattern
var person = function(){
return module = {
setName: function(name){
module.name=name;
}
}
};
var bill = person();
bill.setName('bill');
console.log(bill.name);

This keyword doesn't seem to work like it should [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.
function Foo() {}
Foo.prototype = {
bar: function () {
this.baz();
},
baz: function () {
this.draw();
requestAnimFrame(this.baz);
}
};
Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either
Wrap the method call inside an anonymous function
This way, accessing the baz property and calling it happen at the same time, which is necessary for the this to be set correctly inside the method call.
You will need to save the this from the outer function in a helper variable, since the inner function will refer to a different this object.
var that = this;
setInterval(function(){
return that.baz();
}, 1000);
Wrap the method call inside a fat arrow function
In Javascript implementations that implement the arrow functions feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow anonymous functions preserve the this from the surrounding function so there is no need to use the var that = this trick. To see if you can use this feature, consult a compatibility table like this one.
Use a binding function
A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.
setInterval( this.baz.bind(this), 1000 );
//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);
i made a proxy class :)
function callback_proxy(obj, obj_method_name)
{
instance_id = callback_proxy.instance_id++;
callback_proxy.instances[instance_id] = obj;
return eval('fn = function() { callback_proxy.instances['+instance_id+'].'+obj_method_name+'(); }');
}
callback_proxy.instance_id = 0;
callback_proxy.instances = new Array();
function Timer(left_time)
{
this.left_time = left_time; //second
this.timer_id;
this.update = function()
{
this.left_time -= 1;
if( this.left_time<=0 )
{
alert('fin!');
clearInterval(this.timer_id);
return;
}
}
this.timer_id = setInterval(callback_proxy(this, 'update'), 1000);
}
new Timer(10);

Categories

Resources