javascript构造函数属性

时间:2018-01-09 12:16:23

标签: javascript object constructor

在这个程序中,Complex.trans来自一个单独的函数,或者它是Complex构造函数的一个属性。我已经测试了代码,我的理解是它是一个单独的函数,它确保它的参数是由Complex构造函数创建的。

function Complex(real, imaginary) {
  this.real = 0;
  this.imaginary = 0;
  this.real = (typeof real === 'undefined') ? this.real :parseFloat(real);
  this.imaginary = (typeof imaginary === 'undefined') ? this.imaginary : parseFloat(imaginary);
  this.name = "sagar";
 }
Complex.transform =function (num) {
 var complex;
 complex = (num instanceof Complex) ? num : complex;
 complex = (typeof num === 'number') ? new Complex(num, 0) : num;
 return complex;
};
function display_complex(re, im) {
 if(im === '0') return '' + re;
 if(re === 0) return '' + im + 'i';
 if(im < 0) return '' + re + im + 'i';
 return '' + re + '+' + im + 'i';
}
function complex_num_add(first, second) {
 var num1, num2;
 num1 = Complex.transform(first);
 num2 = Complex.transform(second);
 var real = num1.real + num2.real;
 var imaginary = num1.imaginary + num2.imaginary;
 return display_complex(real, imaginary);
}
 var a = new Complex(2, -7);
 var b = new Complex(4,  3);
 console.log(complex_num_add(a,b)); // 6-4i

1 个答案:

答案 0 :(得分:0)

抱歉,我无法解释原因。但这里有两种做事方式。 (就个人而言,这就是我看待它的方式:有不同的方法。)

<script>
// Constructor function
function Numbers(num) {
  this.value = num;
}

// a member function.  When you define this outside of function Numbers, you need to add .prototype
Numbers.prototype.squareroot = function () {
  return Math.sqrt(this.value);
}

var a = new Numbers(5);
console.log(a.squareroot());

////  another way:

// Constructor function
function Numbers(num) {
  this.value = num;
  // member
  this.squareroot = function () {
    return Math.sqrt(this.value);
  }
}

var b = new Numbers(7);
console.log(b.squareroot());

</script>