zoukankan      html  css  js  c++  java
  • [Javascript] You can't pass a variable

    Let's see a simple code example:

    let pet = "dog"
    console.log(pet)

    We have console.log(pet) inside the code, when you read it, you might say:

    Pass ´pet´ variable to console log function

    Well, actually it is wrong.

    In Javascritp, we cannot pass a variable around, we actually pass a value.

    When javascript read that code, seeing 'pet', it looks for its value first. Then pass the value (which is 'dog') to the console log.

    So to remember in Javascript, we don't pass variable, we pass value.

    Why we need to understand those?

    Let's see another example:

    let x = 10;
    let y = x;
    x = 0;

    What's the value of ´y´?

    The Answer is 10.

    So, in line 1: we assign variable x to the value of 10.   x ---> 10

    line 2: we assgin variable y to the value of x which is 10. It is important here, we didn't assign variable x to the y, we assign value to the y.  y ---> 10

    line 3: we assign variable x to the value 0.  x---> 0

    Therefore, y still holds the value of 10. 

    If you got the answer is 0. Then you might made the mistake, when you see `let y = x`; you might think we assign variable 'x' to 'y', if x changes, y also changes. THAT'S WRONG. Remember, We don't pass variable, we pass value.

    Exercises:

    'feed' function locates in another file, maintained by other people. Is that possible just modify 'feed' function, so that console.log(pets[0]) would output a different value other than 'D'?

    let pets = "Dog and cat";
    feed(pets);
    console.log(pets[0]); // D

    Answer: Not possible. We pass value 'Dog and cat' to the function. It is String type, belongs to primitive type, which is immutable, You cannot mess up with that.


    'feed' function locates in another file, maintained by other people. Is that possible just modify 'feed' function, so that console.log(pets[0]) would output a different value other than 'Dog'?

    let pets = ["Dog", "Cat"];
    feed(pets);
    console.log(pets[0]); // Dog

    Answer: Yes, it is. We still pass the value, not variable to the feed function, but Array is not primitive value, they are 'object'. So you can mutate the value inside function, so it will output soemthingelse other than 'Dog'

  • 相关阅读:
    PHP数据库备份文件分卷导入的实现思路
    用delphi如何实现启动停止windows服务
    【创意logo】第23个世界无烟日 让烟草远离女性
    修改“windows xp资源管理器”的默认打开路径
    PHP百行代码快速构建简易聊天室
    简单的方法实现判断Mysql内某个字段Fields是否存在
    Blackhand的插件管理部分
    PHP 与 ASP.NET 正面交锋
    C语言运算符
    功能齐全的发送邮件类
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12358155.html
Copyright © 2011-2022 走看看