php getter,对象访问器 getter和setter

var person = {

firstName: "Bill",

lastName: "Gates",

language: "en",

get lang() { // 自动解析为 lang: return this.language

return this.language;

},

set lang(value) {

this.language = value;

}

};

console.log(person.lang); // => "en"

person.lang = "chinese";

console.log(person); // => {firstName: "Bill", lastName: "Gates", language: "chinese"}

console.log(person.lang); // => "chinese"

例子1

var person = {

firstName: "Bill",

lastName: "Gates",

fullName: function() {

return this.firstName + " " + this.lastName;

}

};

console.log(person.fullName()); // => Bill Gates 以方法的形式访问

例子2

var person = {

firstName: "Bill",

lastName: "Gates",

get fullName() { // 自动解析为 fullName: "Bill Gates"

return this.firstName + " " + this.lastName;

}

};

console.log(person); // => {firstName: "Bill", fullName: "Bill Gates", lastName: "Gates"}

console.log(person.fullName); // => Bill Gates 以属性形式访问, 提供了更简洁的语法。

模拟js操作客户端的cookie

let doc = {

arp_scroll_position: 414,

PHPSESSID: "65trladb2tjqbikl0fn93akkbu",

get cookie() {

let str = "";

for (let key in this) {

if (key !== "cookie") {

str += key + "=" + this[key] + ";";

}

}

return str.slice(0, -1);

},

set cookie(value) {

let arr = value.split(";");

for (let item of arr) {

let [a, b] = item.split("=");

this[a] = b;

}

}

};

doc.cookie = `app-installed=1; expires=${new Date(

2020,

11,

11

).toGMTString()}`;

console.log(doc); // => {" expires": "Thu, 10 Dec 2020 16:00:00 GMT", PHPSESSID: "65trladb2tjqbikl0fn93akkbu", app-installed: "1", arp_scroll_position: 414, cookie: "arp_scroll_position=414;PHPSESSID=65trladb2tjqbikl0fn93akkbu;app-installed=1; expires=Thu, 10 Dec 2020 16:00:00 GMT"}

console.log(doc.cookie); // => arp_scroll_position=414;PHPSESSID=65trladb2tjqbikl0fn93akkbu;app-installed=1; expires=Thu, 10 Dec 2020 16:00:00 GMT

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值