說明

每天都有XD的事!!

[公告]

『本站提供各類 {整合式教學 + 短評}』

2015年10月27日 星期二

JavaScript Programming Notes - Difference between array and objects / Constructors

JavaScript 

Q: What is the difference between arrays and objects?

A: Array is a type of object, so if we are going to draw out the circle diagram array would be inside the object circle. When an object is created, it will automatically inherit the object prototype functions. This is where arrays and objects start to show their differences. A normal object will only inherit the object prototype functions, whereas arrays will also inherit the Array prototype functions in addition to the object prototype functions.

Q: What would happen if a variable were passed into the constructor of a function, and then the variable is changed, what will happen?


function test(a){
    this.a = a;
}

var b = ['1', '2', '3'];

var something = new test(b);

b.push('4');

console.log(b) //output 1
console.log(something.a) //output 2


A: The a in the test function will be a reference to b. Therefore, output 1 and output 2 will be the same, which is ['1', '2', '3', '4']. One thing to note is that if variable b is now a primitive type data, the value will be passed to the function constructor instead. For example, in the above code snippet, let's assume that variable b = 1. After it is passed into the constructor, the variable a inside test function will always be 1 no matter how you change variable b.

沒有留言:

張貼留言