基本上我试图在object.prototype中添加一个带有我自己的函数的对象。
Object.prototype.personalTest = {
sum: function () {
return this.something + this.other;
}
};
var numbers = {
something: 1,
other: 2
};
console.log(numbers.personalTest.sum());
问题是我无法从原始对象中获取值。这个'这个'关键字使用我的对象作为' this'。
如何更改'这个'的价值?或传递给对象?
修改 我做了这个,它有点工作但不是我想要的
var personalAccess = function () {
var self = this;
this.PersonalTools = {
sum: function () {
return self.something + self.other;
},
minus: function () {
return self.something - self.other;
}
};
};
Object.prototype.personalTest = personalAccess;
var numbers = {
something: 1,
other: 2
};
console.log(numbers.personalTest());
对象不再是原型的一部分,但这不是问题。 问题是,对于每个变量,我必须使用函数构建对象。
console.log(numbers.personalTest());
..........解...........
我最后在javascript上学习了一些技巧,并使用工厂函数来解决我的问题。
(function () {
var myTools = function () {
var self = this;
var tools = {
sum: self.first + self.second
};
return tools;
};
Object.prototype.MyTools = myTools;
}());
答案 0 :(得分:1)
主要问题是,您认为sum
内声明的函数personalTest
可以访问其外的任何属性。函数sum
的范围是对象personalTest
。
另一种方法是将对象numbers
绑定到函数sum
或执行传递对象call
的函数numbers
。
numbers.personalTest.sum.bind(numbers)();
numbers.personalTest.sum.call(numbers);
Object.prototype.personalTest = {
sum: function () {
return this.something + this.other;
}
};
var numbers = {
something: 1,
other: 2
};
console.log(numbers.personalTest.sum.bind(numbers)());
console.log(numbers.personalTest.sum.call(numbers));

或者,您可以将这些值分配给personalTest
,以便可以从函数sum
访问这些值。
Object.prototype.personalTest = {
sum: function () {
return this.something + this.other;
}
};
var numbers = {
something: 1,
other: 2
};
Object.assign(numbers.personalTest, numbers);
console.log(numbers.personalTest.sum());

另一种方法是创建setter和getter以自动将必要的属性设置为personalTest
:
Object.prototype.personalTest = {
sum: function () {
return this.something + this.other;
}
};
var numbers = {
set something(s) {
this.thing = this.personalTest.something = s;
},
get something() {
return this.thing;
},
set other(s) {
this.o = this.personalTest.other = s;
},
get other() {
return this.o;
}
};
numbers.something = 1
numbers.other = 2
console.log(numbers.personalTest.sum());

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
numbers.personalTest.sum.call(numbers)
答案 2 :(得分:0)
代码:
Object.prototype.personalTest = {
sum: function () {
return this.something + this.other;
}
};
为您创建的每个对象添加一个名为personalTest
的新属性。
此属性是一个对象本身,具有一个属性sum
,它是一个函数。在sum()
函数内,this
引用此属性sum()
的对象(即您创建并存储在Object.prototype.personalTest
中的对象)。
您可以通过以下方式调用sum
numbers
来访问var numbers = {
something: 1,
other: 2
};
console.log(numbers.personalTest.sum.call(numbers));
的属性:
sum()
这样,使用personalTest.sum
作为numbers
调用函数this
(只能通过任何对象的属性{{1}}访问)。
详细了解Function.call()
。