var obj = {
resultCodeId: data[i].resultCodes[j].resultCodeId
};
var resultCodeId= data[i].resultCodes[j].resultCodeId;
在JavaScript中,' : '和' = '有什么根本区别?变量是否也能拥有属性,还是只有对象可以拥有属性?
var obj = {
resultCodeId: data[i].resultCodes[j].resultCodeId
};
var resultCodeId= data[i].resultCodes[j].resultCodeId;
在JavaScript中,' : '和' = '有什么根本区别?变量是否也能拥有属性,还是只有对象可以拥有属性?
=
用于对象属性或全局/局部变量的赋值。
:
仅用于对象定义中的属性赋值。
另外: 您可以删除属性。 您不能删除变量。
var obj = {
p1: 'im p1',
p2: 2
};
obj.p1 = 'im updated p1'; // assign a new value to object property
var v = 'just a var'; // is global outside a function and local inside a function
delete obj.p1; // is ok
delete v; // is not ok
如果使用成员函数,会有很大的区别。局部变量可以立即看到,但属性不行。它们需要 this
。但是——这是一个大的区别——有时成员函数完全看不见自己的属性。以下是一些标准代码,具有基本构造函数:
function Cat() { // constructor with a var and property
var a="local a"; // variable
this.b="local b"; // property
this.showBad = function() { return a+", "+b; } // local a, but searches for b in global
this.showGood = function() { return a+", "+this.b; } // local a and b (but has a bug, explained below)
}
var c1=new Cat(); // using the constructor
var a="GLOBAL A", b="GLOBAL B"; // if we can't see c1's locals, we get these
console.log(c1.showBad()); // local a, GLOBAL B // oops on B
console.log(c1.showGood()); // local a, local b // works fine, using "this"
到目前为止,没什么大不了的。属性需要this
关键字,而变量不需要(实际上也不能有)。这只是小问题。但是,在JavaScript成员函数中,this
可能是任何内容。如果您习惯于面向对象编程语言,那似乎是错误的。在这里,我们使用全局作用域调用c1.showGood
,并将this
设置为全局作用域。
var sGood=c1.showGood; // sGood is the function "c1.showGood"
console.log(sGood()); // local a, GLOBAL B // Argg. this.b didn't work!
这似乎是假的,但像这样的事情确实存在。由于这两件事情(变量总是有效的,并且我们需要一种可靠的方式来始终查看我们的属性),一个标准的技巧是在构造过程中将this
锁定在一个变量中。它很好地显示了变量/属性之间的区别:
function Cat() { // constructor with a var and property
var self = this; // self is our permanent, always visible link to this Cat
this.a="local a";
this.b="local b";
this.showGood = function() { return self.a+", "+self.b; }
}
self
是一个变量,因此我们的showGood
总是可以找到自己。同时a
和b
只能通过链接找到,这就是self
所完成的任务。
属性通常与JavaScript对象相关联。
var obj = {
name: 'test', --> property
getName: function(){ --> property
return this.name
}
};
var global = "string"; --> variable
function test(){
var local = "string"; --> variable
}
但是属性和变量的基本概念仍然相同,即存储或指向内存中的对象。
“:”用于将属性与对象关联。
“=”用于将实际数据或引用存储在内存中。
“:”用于以对象方式将键分配给值,作为键/值对。而“=”是一种赋值运算符。它将变量赋值为一个值。
是的,变量可以具有属性,因为变量可以被赋值为一个对象。
:
与创建对象(及其属性)有关
let obj = {prop1: true, prop2: false};
=
在执行过程中与某个定义(变量、函数、对象、属性或其他内容)相关联。
obj.prop1 = false;
obj.prop2 = true;
let foo;
foo = function(){}
let variable;
variable = true;
只有对象具有属性(但几乎所有JS中的东西都是对象;函数是一个对象;我们有全局/窗口对象;等等)
让我们以你的例子来解释一下:
此外:
var resultCodeId= data[i].resultCodes[j].resultCodeId; 在对象/函数内部的这个语句将被视为局部变量,只能在该对象/函数内部访问。