使用文字和自定义构造函数创建Javascript对象

编程入门 行业动态 更新时间:2024-10-25 04:21:50
本文介绍了使用文字和自定义构造函数创建Javascript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道可以使用多种方法在javascript中创建对象,并且我一直在阅读对象字面量语法通常是首选. (正确吗?)

I understand that there are multiple ways to create an object in javascript and I have been reading that object literal syntax is generally preferred. (Correct?)

我一直无法弄清楚的是,是否有理由使用其他任何方式创建对象,例如自定义构造函数(var p = new Person("Adam"))?仅当我想要私有变量或向其原型添加方法或属性时才使用自定义构造函数吗?没有办法用文字来完成这些操作吗?

What I haven't been able to figure out is if there is ever a reason to use any of the other ways to create objects, such as a custom constructor function (var p = new Person("Adam"))? Is it true to use a custom constructor function only if I want private variables or to add methods or properties to its prototype? Is there no way to do these in a literal?

推荐答案

当您要创建类似于Java的对象实例时,可以使用自定义构造函数.

You can use the custom constructor function when you want to create instances of objects, similar to Java.

例如:

function MyObj(x){ this.x = x; } MyObj.prototype.printX = function(){ alert(this.x); } var obj1 = new MyObj("hello"); var obj2 = new MyObj("hello2"); obj1.printX();//prints hello obj2.printX();//prints hello2

现在我有此对象的两个实例.如果我使用String文字,则需要将对象克隆到新的var中,以获得另一个实例.

Now I have two instances of this object. If I used String literals I would need to clone the object into a new var in order to get another instance.

更多推荐

使用文字和自定义构造函数创建Javascript对象

本文发布于:2023-07-14 22:09:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   函数   对象   文字   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!