代码拉取完成,页面将自动刷新
var abc01 = "hello";
var abc02 = {type:1,color:"red"};
对象也是变量,但是对象包含很多值。
var abc = {type:1,color:"red"};
对象定义可横跨多行:
var abc = {
type:1,
color:"red"
};
名称:值对被称为对象的属性
var abc = {
type:1,
color:"red"
};
访问对象属性
abc.color;
abc["color"];
对象也可以有方法。方法以函数定义被存储在属性中。
var abc = {
type:1,
color:"red"
getColor: function(){
return this.color;
}
};
console.log(abc.getColor());
运行结果:
$ node js.js
red
请注意this关键字,在函数定义中,this 指向该函数的“拥有者”,在上面的例子中,this指向abc对象
修改代码,在函数中打印this值
var abc = {
type:1,
color:"red",
getColor:function(){
console.log(this);
return this.color;
}
};
console.log(abc.getColor());
运行结果
$ node js.js
{ type: 1, color: 'red', getColor: [Function: getColor] }
red
如果代码写为:
var abc = {
type:1,
color:"red",
getColor:function(){
return color;
}
};
console.log(abc.getColor());
运行结果如下
$ node js.js
/Users/zhangqixun/temp/js.js:5
return color;
^
ReferenceError: color is not defined
at Object.getColor (/Users/zhangqixun/temp/js.js:5:9)
at Object.<anonymous> (/Users/zhangqixun/temp/js.js:8:17)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
var abc = {
type:1,
color:"red",
getColor:function(){
console.log(this);
return this.color;
}
};
console.log(abc.getColor());
console.log(abc.getColor);
var myColor = abc.getColor;
console.log(myColor);
console.log(myColor());
运行结果如下
$ node js.js
{ type: 1, color: 'red', getColor: [Function: getColor] }
red
[Function: getColor]
[Function: getColor]
<ref *1> Object [global] {
global: [Circular *1],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Getter]
},
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Getter]
}
}
undefined
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。