[英]How do i call a function on another function
我正在嘗試調用一個函數在另一個函數上進行乘法,該函數接受兩個數字作為參數。 我曾嘗試使用構造函數和嵌套函數,但無濟於事。 我嘗試了以下方法:
function Coordinate(a, b) {
var x, y;
return {x: a, y: b};
function multiply(n) {
x * n;
y * n;
}
}
var makeCoordinate = new Coordinate(2,3);
console.log(makeCoordinate.multiple(2));
//預期輸出:4 6;
您應該將multiply
設置為在Coordinate
的原型上,以便在調用new Coordinate
,實例化的對象將使用multiply
作為方法。 為了使其正常工作,還應該設置this.x
和this.y
而不是直接返回對象:
function Coordinate(a, b) { this.x = a; this.y = b; } Coordinate.prototype.multiply = function(n) { this.x *= n; this.y *= n; return this; } var makeCoordinate = new Coordinate(2,3); console.log(makeCoordinate.multiply(2));
或者,如果您希望multiply
不返回原始對象而只返回相乘的坐標,則僅返回坐標:
function Coordinate(a, b) { this.x = a; this.y = b; } Coordinate.prototype.multiply = function(n) { return [this.x * n, this.y * n]; } var makeCoordinate = new Coordinate(2,3); console.log(makeCoordinate.multiply(2));
答案修改了兩部分:
希望這個幫助:)
function Coordinate(a, b) { this.x = a; this.y = b; this.multiply = function(n) { return this.x * n + " " + this.y * n; } } var makeCoordinate = new Coordinate(2,3); console.log(makeCoordinate.multiply(2));
好吧,首先,您的console.log正在調用多個,而不是多個。
其次,嘗試這樣的方法:
function Coordinate( a, b )
{
function multiply( n )
{
this.x = this.x * n;
this.y = this.y * n;
return this;
}
var co = { x: a, y : b };
co.multiply = multiply.bind( co );
return co;
}
在評論中澄清后,(最簡單的)解決方案是:
// important code function Coordinate(a,b) { this.x = a; this.y = b; this.multiply = function (n) { this.x = this.x*n; this.y = this.y*n; } } // test code let coord = new Coordinate(2,3); console.log("Original Coordinate:"); console.log(coord); coord.multiply(2); console.log("Changed Coordinate: "); console.log(coord);
如果您不希望在每個Coordinate對象中都復制該函數,也可以將其放入原型中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.