原型为数组的JavaScript对象成员将被所有类实例共享以前有人注意到这种行为吗?这真的把我甩了.。我希望原型数组对每个类实例都是私有的,而不是在所有类实例之间共享。有人能证实这是正确的行为吗?也许能更详细地解释这一行为吗?注意注释的代码以及它如何影响脚本的行为。<html><head><script type="text/javascript">function print_r( title, object ) {
var output = '';
for( var key in object ) {
output += key + ": " + object[ key ] + "\n";
}
output = title + "\n\n" + output;
alert( output );}function Sandwich() {
// Uncomment this to fix the problem
//this.ingredients = [];}Sandwich.prototype = {
"ingredients" : [],
"addIngredients" : function( ingArray ) {
for( var key in ingArray ) {
this.addIngredient( ingArray[ key ] );
}
},
"addIngredient" : function( thing ) {
this.ingredients.push( thing );
}}var cheeseburger = new Sandwich();cheeseburger.addIngredients( [ "burger", "cheese" ] );var blt = new Sandwich();blt.addIngredients
( [ "bacon", "lettuce", "tomato" ] );var spicy_chicken_sandwich = new Sandwich();spicy_chicken_sandwich.addIngredients(
[ "spicy chicken pattie", "lettuce", "tomato", "honey dijon mayo", "love" ] );var onLoad = function() {
print_r( "Cheeseburger contains:", cheeseburger.ingredients );};</script></head><body onload="onLoad();"></body></html>非常感谢。
3 回答
POPMUISE
TA贡献1765条经验 获得超5个赞
[]
new Array()
Obj.prototype = {...}
添加回答
举报
0/150
提交
取消