简体   繁体   English

为什么我不能在javascript中向字符串对象添加属性?

[英]Why can't I add properties to a string object in javascript?

I inherited some javascript code another developer wrote. 我继承了其他开发人员编写的一些JavaScript代码。 He didn't like the grid component we used throughout the project, so he decided to write his own. 他不喜欢我们在整个项目中使用的网格组件,因此他决定编写自己的网格组件。 The grid he wrote can't sort dates, because it can only bind to strings / numbers. 他编写的网格无法对日期进行排序,因为它只能绑定到字符串/数字。 He converts all dates to strings before using them. 他在使用日期之前将所有日期转换为字符串。 I looked at the string formatting of date function he wrote, and figured I could just add a date property to the string with the original value, and then when sorting see if the string has a date property and sort based on that. 我查看了他编写的date函数的字符串格式,并认为我可以将一个date属性添加到具有原始值的字符串中,然后在排序时查看该字符串是否具有date属性并基于该属性进行排序。 However, it seems like you can't add properties to strings in javascript. 但是,似乎无法将属性添加到javascript中的字符串。 I wasn't aware there were certain types you can't add properties to. 我不知道某些类型无法添加属性。 For example: 例如:

<html>
<script>
var test = "test";
test.test = "test inner";
console.log(test);
console.log(test.test);
</script>

test.test will be undefined. test.test将是不确定的。 Weird. 奇怪的。 My question is why this code doesn't work? 我的问题是为什么此代码不起作用? And also, if you can think of any workarounds for sorting dates on that grid (besides actually binding to date objects instead of strings, which would be a pain to fix,) that would be really helpful. 而且,如果您能想到在该网格上对日期进行排序的任何变通方法(除了实际上绑定到日期对象而不是字符串,这很麻烦解决),这将非常有用。

There are 6 language types in JavaScript: JavaScript有6种语言类型:

  • 5 primitive types: String , Number , Boolean , Null , Undefined 5种原始类型: 字符串数字布尔值未定义
  • 1 non-primitive type: Object 1个非基本类型: 对象

Values of the primitive types are called primitive values and they cannot have properties. 基本类型的值称为基本值,它们不能具有属性。
Values of the Object non-primitive type are called objects an they can have properties. 对象非基本类型的值称为对象,它们可以具有属性。

When you try to assign a property named 'bar' to a variable foo , like so: 当您尝试将名为'bar'的属性分配给变量foo ,如下所示:

foo.bar = 'abc';

then the result will depend on the type of the value of foo : 那么结果将取决于foo值的类型:

(a) if the value of foo is of the type Undefined or Null , then an error will be thrown, (a)如果foo的值为UndefinedNull类型,则将引发错误,

(b) if the value of foo is of the type Object , then a named property 'bar' will be defined on the object foo (if necessary), and its value will be set to 'abc' , (b)如果foo的值属于Object类型,则将在对象foo上定义一个命名属性'bar' (如有必要),并将其值设置为'abc'

(c) if the value of foo is of the type Number , String or Boolean , then the variable foo will not be changed in any way. (c)如果foo的值是NumberStringBoolean类型,则变量foo不会以任何方式更改。 In this case, the above assignment operation will be a noop . 在这种情况下,上述分配操作将为noop

So, as you can see, assigning properties to variables only makes sense if those variables are objects. 因此,如您所见,仅在变量是对象的情况下,才将属性分配给变量。 If that is not the case, then the assignment will either do nothing at all, or even throw an error. 如果不是这种情况,则分配将根本不执行任何操作,甚至抛出错误。


In your case, the variable test contains a value of the type String , so this: 在您的情况下,变量test包含String类型的值,因此:

test.test = "test inner";

does nothing at all. 什么都不做。


However, since ES5 introduced accessor properties, there is an exception to what I've said above. 但是,由于ES5引入了访问器属性,所以我上面已经说过了。 Accessor properties allow us to define functions which are invoked whenever the property is either retrieved or set. 访问器属性使我们可以定义在检索或设置属性时将调用的函数。

For instance: 例如:

var str = '';
str.prop;

Here str is a variable holding a String value. 在这里, str是一个包含String值的变量。 Therefore, accessing a property of that variable should be a no-op ( str.prop merely returns undefined ). 因此,访问该变量的属性应该是no-op( str.prop仅返回undefined )。 This is true with one exception: if String.prototype contains a accessor property 'prop' with a defined getter, then that getter will be invoked. 唯一的例外是正确的:如果String.prototype包含具有定义的getter的访问器属性'prop' ,则将调用该getter。

So, if this is defined: 因此,如果已定义:

Object.defineProperty( String.prototype, 'prop', {
    get: function () {
        // this function is the getter
    }
}); 

then this 然后这个

str.prop;

will invoke that getter function. 将调用该getter函数。

Live demo: http://jsfiddle.net/fmNgu/ 现场演示: http //jsfiddle.net/fmNgu/

However, I don't think that adding accessor properties to the built-in prototypes would be a good practice. 但是,我认为将访问器属性添加到内置原型中并不是一个好习惯。

If you use a String object you can add properties: 如果使用String对象,则可以添加属性:

var test = new String("test");
test.test = "test inner";
console.log(test.toString()); // prints out "test"
console.log(test.test); // prints out "test inner"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript - 为什么我不能向“字符串”对象添加新属性? - JavaScript - Why can't I add new attributes to a “string” object? 如何将自定义属性添加到javascript字符串对象 - how can i add custom properties to javascript string object 为什么我不能在JavaScript中获取导航器对象的属性数? - Why can't I get properties count of navigator object in JavaScript? 为什么我无法在javascript中访问对象属性? - Why can't I access object properties in javascript? 为什么不能在 JavaScript 中设置数组元素(字符串)的属性? - Why can't I set properties of an array element (a string) in JavaScript? 为什么我不能准备好这个 Object 属性? - Why can't I ready this Object properties? 为什么不能在JavaScript中将对象属性设置为空字符串? - Why can't I set object property to empty string in JavaScript? 为什么在循环对象时不能显示属性的属性? - Why can't I the properties of properties when looping an object? 为什么我不能更新更新我的JavaScript对象属性值? - Why I can't update update my JavaScript object properties value? 为什么我们不能像在javascript中为对象常量那样向函数体内的函数对象添加属性? - Why can't we add properties to a function object inside function body like we do for object literals in javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM