如果我需要一个对象到另一个对象中以便在函数中使用,哪个是最好的?
function A() {
this.alert = function () {
console.log(b.value);
}
this.alert2 = function () {
console.log(this.value);
}
}
function B() {
this.value = 'test';
}
var a = new A();
var b = new B();
A.prototype.b = b;
// Option 1
`a.alert();`
// Option 2
`a.alert2.apply(b);`
我相信选项 2 更好,因为仅在一个函数中使用对象 (b)。
最佳答案
原型(prototype)要容易得多,但我会以相反的方式使用它:
function B() {
this.value = 'test';
}
B.prototype.alert = function() {
console.log(this.value);
}
var b = new B();
b.alert();
如果您想使用不同对象的函数/方法,您应该给它一个参数(而不是像 b
函数中那样使用隐式全局 a.alert
变量):
var a = {
alert: function(x) {
console.log(x.value);
}
};
a.alert(b);
或者当你有一个方法时继承它,例如:
var a = {
value: "a test",
alert: function() {
console.log(this.value);
}
};
// =============================
function B() {
this.value = 'test';
}
B.prototype.alert = a.alert; // mixin inheritance
var b = new B();
b.alert();
关于javascript - 原型(prototype)与 JavaScript 中的应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579426/