JavaScript语言和其它主流编程语言一样,是可以创建对象的,对象有构造方法,还有属性和调用方法,有私有的也有公开的,下面有讲如何写定义
- 写一个对象文件,例如,猫
./common/lib/cat.js
代码如下
export default class Cat {
//---------以下带#都是定义私有的属性和方法 外部不能访问和修改 类似其它语言的private _
#name = name || "猫";
#content = "hello";
#location = { x:0, y:0 };
/**
* 移动位置的方法 外部不能调用 private
* @param {Integer} x
* @param {Integer} y
*/
#moveLocation = (x,y) => {
this.#location.x = x;
this.#location.y = y;
}
//---------以下都是定义公开的属性和方法 类似其它语言的public
// state = '11';
// color = 'black';
// _prop = 'public';
/*
* 这是构造方法 new Object() 会自动调用
* @param { String } name 可传参 猫的名字
*/
constructor(name){
//---------带# 私有的属性 可修改
this.#name = name || "黑猫";
//---------以下都是定义公开的属性和方法 供外部访问和调用 类似其它语言的public
this.state = '11';
this.color = 'black';
this._prop = 'public';
// 获取猫所在的位置
this.getLocation = () => {
return this.#location;
}
//上面带=>箭头是简写的 省略了function 原来如下
//this.getLocation = function () {
// return this.#location;
//}
}
//---------以下都是公开的方法 供外部调用 public
/**
* 猫叫
* */
call(){
console.log('cat '+this.#name+' say '+this.#content);
}
/**
* 指定位置方法 public
* @param { Integer } x
* @param { Integer } y
* */
toLocation(x,y){
this.#moveLocation(x,y);
}
/**
* 获取猫的名字
* @return { String }
* */
getName(){
return this.#name;
}
/**
* 获取猫的声音内容
* @return { String }
* */
getContent(){
return this.#content;
}
/**
* 设置猫的声音内容
* @param { String } content
* */
setContent(content){
this.#content = content;
}
}
- 导入对象运用
在需要使用的代码中,写相对路径中的cat.js
文件正确导入import
即可创建对象,代码如下
import Cat from "./common/lib/cat.js";
export default {
//...
mounted(){
//创建对象猫 实例
let cat = new Cat('Tom');
//调用对象的方法
cat.call();
//打印日志输出
console.log("cat object",cat);
//测试报告
// console.log("cat object test 1",cat.name);//私有属性无法访问
// console.log("cat object test 2",cat.state);
// console.log("cat object test 3",cat.moveLocation());//私有方法无法调用
// console.log("cat object test 4",cat.getLocation());
}
//...
}
创建对象的步骤很简单,与其它编程语言不同的是,会发现这里import * from *
引用前需要去加export default
代码,记住就对了,就讲到这里,如还有什么不清楚的,请在结尾处留言
💡 请注意
- 文章中代码使用了 Vue技术写法,建议学习
- JavaScript 需要支持 ES5 以上语法