5

## 以陣列為參數傳入來產生物件

function 的參數傳入陣列，用apply的方法可解決：

``````function call_me(x,y) {
console.log(x);
console.log(y);
};

call_me(1,2);
var arrary = [1,2];
call_me(array); // --> call_me(array,undefined)

call_me.apply(null,array);
call_me.apply(this,array);
``````

``````var create_me = function(x,y) {
this.x = x;
this.y = y;
}

var one = new create_me(1,2) // -> Object { x=1, y=2 }
var two = new.create_me.apply(array) // SyntaxError: syntax error
``````

Use of .apply() with 'new' operator. Is this possible?

``````var build_me = function() {
function F(args) {
return create_me.apply(this, args);
}
F.prototype = create_me.prototype;

return function(args) {
return new F(args);
}
}();

build_me(array) // -> Object { x=1, y=2 }
``````

JavaScript 函式與 new 運算子

(這地方有誤解嗎？)

``````var foo = {};
var bar = function() {};
typeof(foo); // -> "object"
typeof(bar); // -> "function"
new foo; // -> TypeError: foo is not a constructor
new bar; // -> Object { }
typeof(new bar); // -> "object"
``````

build_me(array) // -> F { x=1, y=2 }

create_me.prototype // -> Object { }

F.prototype // -> Object { }

### 6 則留言

0
dojo3000
iT邦新手 4 級 ‧ 2012-12-03 12:15:58

``````&lt;pre class="c" name="code">
var arr = [1,2,3];

var Sum = function(numbers){
var _size = numbers.length;
var _total = 0;

for(var i=0;i&lt;_size;i++){
_total += numbers[i]
}

this.total = _total;
}

var s = new Sum(arr);

s.total // 等於6
``````
0

iT邦大師 1 級 ‧ 2012-12-03 15:49:06

dojo3000 iT邦新手 4 級 ‧ 2012-12-03 18:31:09 檢舉

0
fillano
iT邦超人 1 級 ‧ 2012-12-07 11:32:01

``````&lt;pre class="c" name="code">
var a = {
base: 1,
init: function() {
return this.base+c;
}
}
};
var b = new a.init();
``````

``````&lt;pre class="c" name="code">
var a = {
base: 1,
init: function() {
this.base = 2;
return this.base+c;
}
}
};
var b = new a.init();
``````
fillano iT邦超人 1 級 ‧ 2012-12-07 11:35:49 檢舉

``````&lt;pre class="c" name="code">
var a = {
base: 1,
init: function() {
return this.base+c;
}
}
};
a.init.prototype = a;
var b = new a.init();
``````
0
gituest
iT邦新手 5 級 ‧ 2013-01-01 13:48:38

a=b ,b=c,a=c.

0
gituest
iT邦新手 5 級 ‧ 2013-01-01 13:48:50

<script>
var create_me = function(x,y) {
this.x = x;
this.y = y;
return({m:x,n:y});
// return {this.x:x,this.y:y} ;
return z ;
}
<script>
var create_me = function(x,y) {
this.x = x;
this.y = y;
return({m:x,n:y});

}
var arr = [1,2];
var one = new create_me(1,2); // -> Object { x=1, y=2 }
two=create_me.apply(arr);

for (x in one) document.write(x);
document.write("<p>one.m::>"+one.m);
document.write("<p>one.n::>"+one.n);
for (y in two) {
document.write("<br>"+y)};
document.write("<p>two.m::>"+two.m);
document.write("<p>two.n::>"+two.n);
</script>

0
gituest
iT邦新手 5 級 ‧ 2013-01-01 13:52:25