14 Star 81 Fork 23

北京大学-张齐勋 / 移动端开发入门实践

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JS_对象.md 3.12 KB
一键复制 编辑 原始数据 按行查看 历史
张齐勋 提交于 2021-04-12 21:50 . 对象是可以嵌套的

变量与对象

var abc01 = "hello";

var abc02 = {type:1,color:"red"};

对象也是变量,但是对象包含很多值。

对象定义

  • 定义(创建)了一个 JavaScript 对象abc
  • 对象中的内容以“名称:值对"的方式来书写(名称和值由冒号分隔,多个内容用逗号隔开)。
  • 如果属性名是一个合法的Javascript的标识符且不是保留字,则并不强制要求用引号括朱属性名。
  • 对象是可以嵌套的
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
JavaScript
1
https://gitee.com/ss-pku/webdev.git
git@gitee.com:ss-pku/webdev.git
ss-pku
webdev
移动端开发入门实践
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891