4 回答

TA貢獻1821條經(jīng)驗 獲得超6個贊
通過將其添加到原型中,您可以將其作為實例方法/屬性使用。為了讓它按照您想要的方式運行,您需要將其直接添加到 Work:
Worker.jobs = 0;
Worker.Work = function () {
++this.jobs;
return this.jobs;
}
那么你甚至可以這樣做:
Worker.prototype.work = () => {
console.log("jobs finished", this.name, Worker.Work());
}

TA貢獻1786條經(jīng)驗 獲得超11個贊
您調(diào)用的函數(shù)位于原型對象中。但它所指的“this”位于子對象中。僅當該屬性不存在時,此[propertyname] 查找才會沿著原型鏈向上進行。
// ++this.jobs is a short for this.jobs = this.jobs +1;
// if the child object is missing this.jobs property, it is fetched from the prototype object. So this assigns the 'jobs' property to current object, but looks it up from the prototype object.
Worker.prototype.Work = function () {
console.log("jobs finished", this.name, ++this.jobs);
}

TA貢獻1828條經(jīng)驗 獲得超13個贊
“this”的使用是指上下文(閉包)。要訪問共享屬性,您應(yīng)該使用“prototype”來代替,以按預(yù)期工作:
var Worker = function (name) {
this.name = name;
}
Worker.prototype.jobs = 0;
Worker.prototype.Work = function () {
console.log("jobs finished", this.name, ++Worker.prototype.jobs);
}
var ca = new Worker("ca");
var cb = new Worker("cb");
ca.Work();// shows 1
cb.Work();// shows 1 (Q: Why is this not printed 2 ?)

TA貢獻1812條經(jīng)驗 獲得超5個贊
當您讀取this.jobs屬性時,查找首先發(fā)生在對象實例本身作為自己的屬性上,當找不到它時,查找發(fā)生在原型鏈上。
因此,由于該jobs屬性是在初始化為 的原型上找到的0,因此該值是從原型中讀取的。
當您遞增 時this.job,這將在遞增操作后創(chuàng)建一個自己的屬性,這就是為什么我們永遠不會看到另一個實例中的更改,因為 成為jobs該特定實例的自己的屬性:
var Worker = function (name) {
this.name = name;
}
Worker.prototype.jobs = 0;
Worker.prototype.Work = function () {
console.log("jobs is an own property =>", this.hasOwnProperty("jobs"));
++this.jobs
console.log("jobs is now an own property =>", this.hasOwnProperty("jobs"));
console.log("jobs finished", this.name, this.jobs);
}
var ca = new Worker("ca");
var cb = new Worker("cb");
ca.Work();// shows 1
cb.Work();// shows 1
另一方面,如果您直接更改原型上的屬性,您可以看到更改也反映在第二個實例上:
var Worker = function (name) {
this.name = name;
}
Worker.prototype.jobs = 0;
Worker.prototype.Work = function () {
++Object.getPrototypeOf(this).jobs
console.log("jobs finished", this.name, this.jobs);
}
var ca = new Worker("ca");
var cb = new Worker("cb");
ca.Work();// shows 1
cb.Work();// shows 2
添加回答
舉報