纯粹的JavaScript可以实现只读属性?

看看mozilla文档 ,看看正则expression式示例(标题为“使用匹配结果创build数组”),我们有如下的语句:

input:反映正则expression式匹配的原始string的只读属性。

index:只读属性,是string中匹配项的从零开始的索引。

等等…是否有可能在JavaScript中创build自己的对象,这些对象将具有只读属性,或者这是保留给特定浏览器实现的内置types的特权?

编辑:由于这个答案写了,使用Object.defineProperty一个新的,更好的方法已经在EcmaScript 5中被标准化,在新的浏览器支持。 见Aidamina的答案 。 如果您需要支持“较旧”的浏览器,则可以使用此答案中的一种方法作为回退。


在Firefox,Opera 9.5+和Safari 3+,Chrome和IE(通过v11testing)中,您可以定义getter和setter属性。 如果您只定义了一个getter,它将有效地创build一个只读属性。 您可以使用对象字面值或通过调用对象上的方法来定义它们。

 var myObject = { get readOnlyProperty() { return 42; } }; alert(myObject.readOnlyProperty); // 42 myObject.readOnlyProperty = 5; // Assignment is allowed, but doesn't do anything alert(myObject.readOnlyProperty); // 42 

如果你已经有一个对象,你可以调用__defineGetter____defineSetter__

 var myObject = {}; myObject.__defineGetter__("readOnlyProperty", function() { return 42; }); 

当然,这在networking上并不是很有用,因为它在Internet Explorer中不起作用。

您可以从John Resig的博客或Mozilla开发人员中心了解更多信息。

使用任何实现ECMAScript 5的javascript解释器,您可以使用Object.defineProperty来定义只读属性。 在松散模式下,解释器将忽略对属性的写入,在严格模式下它将抛出exception。

来自ejohn.org的示例:

 var obj = {}; Object.defineProperty( obj, "<yourPropertyNameHere>", { value: "<yourPropertyValueHere>", writable: false, enumerable: true, configurable: true }); 

可以通过getter方法在JavaScript中拥有只读属性。 这通常被称为“模块”模式。

YUI博客有一个很好的写作:http: //yuiblog.com/blog/2007/06/12/module-pattern/

post片段:

 YAHOO.myProject.myModule = function () { //"private" variables: var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule."; //"private" method: var myPrivateMethod = function () { YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule"); } return { myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty." myPublicMethod: function () { YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod."); //Within myProject, I can access "private" vars and methods: YAHOO.log(myPrivateVar); YAHOO.log(myPrivateMethod()); //The native scope of myPublicMethod is myProject; we can //access public members using "this": YAHOO.log(this.myPublicProperty); } }; }(); // the parens here cause the anonymous function to execute and return 

作为只读属性或variables在这里。

正如aidamina所说的 , 顺便提一句 ,这里是一个testing的简短代码,现在JQuery假装不赞成使用selector属性。

 <script> Object.defineProperties(window, { "selector": { value: 'window', writable: false } }); alert (window.selector); // outputs window selector ='ddd'; // testing because it belong to the global object alert (window.selector); // outputs window alert (selector); // outputs window window.selector='abc'; alert (window.selector); // outputs window alert (selector); // outputs window </script> 

所以你有一个只读属性或variablestesting。

是的,我们只能读取JavaScript中的对象的属性。 它可以通过私有variables和object.defineproperty()方法来实现,

看下面的例子,它说明了具有只读属性的对象,

 function Employee(name,age){ var _name = name; var _age = age; Object.defineProperty(this,'name',{ get:function(){ return _name; } }) } var emp = new Employee('safeer',25); console.log(emp.name); //return 'safeer' emp.name='abc'; console.log(emp.name); //again return 'safeer', since name is read-only property 

这里是道格拉斯·克罗克福德(Douglas Crockford)在“Private Members in Javascript”页面上的链接。在我看来,只有在只提供getter方法的情况下,这些才会被读取,而且没有setter:

http://javascript.crockford.com/private.html

bob.js框架提供了一种声明只读属性的方法。 底下,它声明一个私人领域,并公开它的getter / setter函数。 bob.js提供了多种方式来做同样的事情,这取决于方便性和特定的目标。 以下是一个使用Property的面向对象实例的方法(其他方法允许在对象本身上定义setter / getters):

 var Person = function(name, age) { this.name = new bob.prop.Property(name, true); var setName = this.name.get_setter(); this.age = new bob.prop.Property(age, true); var setAge = this.age.get_setter(); this.parent = new bob.prop.Property(null, false, true); }; var p = new Person('Bob', 20); p.parent.set_value(new Person('Martin', 50)); console.log('name: ' + p.name.get_value()); console.log('age: ' + p.age.get_value()); console.log('parent: ' + (p.parent.get_value ? p.parent.get_value().name.get_value() : 'N/A')); // Output: // name: Bob // age: 20 // parent: N/A 

最后, p.name.set_value没有被定义,因为这是一个只读属性。

你会看到我已经定义了一个setter和getter的颜色,所以可以修改。 一旦对象被定义,品牌就变成只读。 我相信这是你正在寻找的function。

  function Car(brand, color) { brand = brand || 'Porche'; // Private variable - Not accessible directly and cannot be frozen color = color || 'Red'; // Private variable - Not accessible directly and cannot be frozen this.color = function() { return color; }; // Getter for color this.setColor = function(x) { color = x; }; // Setter for color this.brand = function() { return brand; }; // Getter for brand Object.freeze(this); // Makes your object's public methods and properties read-only } function w(str) { /*************************/ /*choose a logging method*/ /*************************/ console.log(str); // document.write(str + "<br>"); } var myCar = new Car; var myCar2 = new Car('BMW','White'); var myCar3 = new Car('Mercedes', 'Black'); w(myCar.brand()); // returns Porche w(myCar.color()); // returns Red w(myCar2.brand()); // returns BMW w(myCar2.color()); // returns White w(myCar3.brand()); // returns Mercedes w(myCar3.color()); // returns Black // This works even when the Object is frozen myCar.setColor('Green'); w(myCar.color()); // returns Green // This will have no effect myCar.color = 'Purple'; w(myCar.color()); // returns Green w(myCar.color); // returns the method // This following will not work as the object is frozen myCar.color = function (x) { alert(x); }; myCar.setColor('Black'); w( myCar.color( 'This will not work. Object is frozen! The method has not been updated' ) ); // returns Black since the method is unchanged 

以上已经在Chromium版本41.0.2272.76 Ubuntu 14.04上进行了testing,并产生了以下输出:

  Porche Red BMW White Mercedes Black Green Green function () { return color; } Black