Jump to content

Call and argument passing


Matej
 Share

Recommended Posts

Hello , i have a questions

if i got it right , if i use call or apply , the function or object which is this code executed in with inherit specific properties ,

for example

function a(args){    b.apply(this,arguments); // here we said , that function a should inherit stuffs from function B , it does inherit alert("lol") , but why doesnt it inherit x also?     alert(x);} function b(){   alert("lol");var x=9;} a(); [/code] and second questionargument passing can be done by value or refference , value is usually primitive varriable like string or numberand refference is usually object. If i set [code]var g=9function call(x){x+=9;}call(g)[/code]

var g inside function equals 18 , but globaly variable g still equals 9 , so why when i set

var person=new Object;function call(x){x.name="david"}call(person)

here if i call person.name outside of the function it equals "david" bcs i created copy of "person" and both of them reffer to one object in header;

so why when i do this

http://jsfiddle.net/nj5a84hm/ person.name="lol" and not "kek"? object should be passed by refference.

(if objects are passed by value , person.name should be undeffined)

 

Could someone explain it to me? thanks for answers

Edited by Matej
Link to comment
Share on other sites

Using Function.apply or Function.call is not about inheritance, it is about scope. In function a you're just saying to call function b in the same scope where function a is running. Declaring the local variable x inside b does not also declare it inside a, once b ends then x gets destroyed because it is a local variable inside b. If you used this.x inside both functions then they would refer to the same thing, because they are both running in the same scope.

person.name="lol" and not "kek"? object should be passed by refference.

It does get passed by reference, but when you make x a new object you are no longer changing the object that was passed to the function, now it's a different object. The object outside of the function does not get changed when you set the variable x to a new object inside the function.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...