Javascript:如何在引用中存储对象

时间:2016-06-06 19:22:06

标签: javascript

我是Javascript的新手,我感到非常困惑。

我创建了一个对象,

var recipe = {name:"", price:10, details:"", img_path:""};

我创建了一个类似于构造函数的函数。它为对象的属性提供值

function recipeInstantiation( name, price, details, img_path){
        recipe.name = name;
        recipe.price = price;
        recipe.details=details;
        recipe.img_path = img_path;
        // I dont know what to return here
        //maybe return recipe;
}

然后我需要将配方对象传递给引用,

var recipe2 = recipe;

这是对的吗?

4 个答案:

答案 0 :(得分:1)

var recipe2 = recipe;

你是对的。通过上述操作,修改recipe2中的任何值也将修改recipe的值,因为JavaScript中的几种类型(如数组和对象)将作为引用传递。

(仅供参考,如果您希望在其他一些用例中将recipe作为参考传递,则应创建一个复制所有{{}的新对象1}}的值,但这超出了这个问题的范围。)

答案 1 :(得分:1)

使用(大写第一个字母)。使用初始化

function Recipe(name, details, ...) {
    this.name = name,
    this.details = details,
    ...
}

使用原型

向该类添加一个函数
Recipe.prototype.getInfo = function() {
    return obj;
}

完整示例:

function Recipe(name, price, details, img_path) {
        this.name = name;
        this.price = price;
        this.details = details;
        this.img_path = img_path;
}

Recipe.prototype.getInfo = function() {
    return {
        name: this.name,
        price: this.price,
        details: this.details,
        img_path: this.img_path
    }
}

var recipe1 = new Recipe("tomatonoodles", 7.99, "without gluten", "img/tomato.jpg");
var info = recipe1.getInfo();

alert(info);

答案 2 :(得分:0)

对象是引用类型,您的类定义应遵循javascript语言结构和约定(即对类使用pascal case)

去这里学习 http://www.w3schools.com/js/js_objects.asp

----------------------------------

    //class definition that describes a recipe
    function Recipe( name, price, details, img_path){
    //javascript use this keyword to define data fields.
            this.name = name;
            this.price = price;
            this.details=details;
            this.img_path = img_path;

    }


    function displayRecipe(recipe){
         //display recipe as html
    }


----------------------------------
    var newReceipe = new Recipe("Pasta", 1000, "Something", "img/pasta.jpg");
    displayRecipe(newReceipe )

答案 3 :(得分:0)

这是更有效的方式。

const newRecipe = (name, price, details, img_path) => {
  const obj = {};
  obj.name = name;
  obj.price = price;
  obj.details = details;
  obj.img_path = img_path;
  return obj;
}

const recipe1 = newRecipe('pasta', 1000, 'something', 'img/pasta.jpg');
console.log(recipe1);