JavaScript对象中的构造方法

JavaScript KoaJS

Tom泡芙

2020-03-30

JavaScript类/对象可以具有构造函数吗?它们是如何创建的?

第3833篇《JavaScript对象中的构造方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

10个回答
Mandy 2020.03.30

在大多数情况下,您必须以某种方式声明所需的属性,然后才能调用传递此信息的方法。如果您不必一开始设置属性,则可以像这样在对象内调用方法。可能不是最漂亮的方法,但这仍然有效。

var objectA = {
    color: ''; 
    callColor : function(){
        console.log(this.color);
    }
    this.callColor(); 
}
var newObject = new objectA(); 
阳光GO 2020.03.30

这里我们需要注意Java脚本中的一点,它是一种无类语言,但是我们可以通过使用Java脚本中的函数来实现。实现此目的的最常见方法是,需要在Java脚本中创建一个函数,并使用new 关键字创建一个对象,然后使用 关键字定义属性和方法。下面是示例。

// Function constructor

   var calculator=function(num1 ,num2){
   this.name="This is function constructor";
   this.mulFunc=function(){
      return num1*num2
   };

};

var objCal=new calculator(10,10);// This is a constructor in java script
alert(objCal.mulFunc());// method call
alert(objCal.name);// property call

//Constructors With Prototypes

var calculator=function(){
   this.name="Constructors With Prototypes";
};

calculator.prototype.mulFunc=function(num1 ,num2){
 return num1*num2;
};
var objCal=new calculator();// This is a constructor in java script
alert(objCal.mulFunc(10,10));// method call
alert(objCal.name); // property call
Gil伽罗小宇宙 2020.03.30

从上面使用Blixt的出色模板时,我发现它不能与多级继承(MyGrandChildClass扩展MyChildClass扩展MyClass)配合使用-反复调用第一个父级的构造函数。因此,这是一个简单的解决方法-如果您需要多级继承,而不是将this.constructor.super.call(this, surName);use chainSuper(this).call(this, surName);与链定义的函数一起使用,如下所示:

function chainSuper(cls) {
  if (cls.__depth == undefined) cls.__depth = 1; else cls.__depth++;
  var depth = cls.__depth;
  var sup = cls.constructor.super;
  while (depth > 1) {
    if (sup.super != undefined) sup = sup.super;
    depth--;
  }
  return sup;
}
蛋蛋 2020.03.30

http://www.jsoops.net/对于Js中的oop非常有用。如果提供私有,受保护的公共变量和函数,以及继承功能。示例代码:

var ClassA = JsOops(function (pri, pro, pub)
{// pri = private, pro = protected, pub = public

    pri.className = "I am A ";

    this.init = function (var1)// constructor
    {
        pri.className += var1;
    }

    pub.getData = function ()
    {
        return "ClassA(Top=" + pro.getClassName() + ", This=" + pri.getClassName()
        + ", ID=" + pro.getClassId() + ")";
    }

    pri.getClassName = function () { return pri.className; }
    pro.getClassName = function () { return pri.className; }
    pro.getClassId = function () { return 1; }
});

var newA = new ClassA("Class");

//***Access public function
console.log(typeof (newA.getData));
// function
console.log(newA.getData());
// ClassA(Top=I am A Class, This=I am A Class, ID=1)

//***You can not access constructor, private and protected function
console.log(typeof (newA.init));            // undefined
console.log(typeof (newA.className));       // undefined
console.log(typeof (newA.pro));             // undefined
console.log(typeof (newA.getClassName));    // undefined
Near猪猪 2020.03.30

如果您使用Typescript,它们会这样做-MicroSoft的开源软件:-)

class BankAccount {
 balance: number;
 constructor(initially: number) {
 this.balance = initially;
 }
 deposit(credit: number) {
 this.balance += credit;
 return this.balance;
 }
}

Typescript可让您“伪造”被编译为javascript构造的OO构造。如果您正在启动一个大型项目,则可能会节省大量时间,并且它刚刚达到里程碑1.0版本。

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

上面的代码被“编译”为:

var BankAccount = (function () {
    function BankAccount(initially) {
        this.balance = initially;
    }
    BankAccount.prototype.deposit = function (credit) {
        this.balance += credit;
        return this.balance;
    };
    return BankAccount;
})();
村村 2020.03.30

我想我会发布有关javascript闭包的信息,因为还没有人使用闭包。

var user = function(id) {
  // private properties & methods goes here.
  var someValue;
  function doSomething(data) {
    someValue = data;
  };

  // constructor goes here.
  if (!id) return null;

  // public properties & methods goes here.
  return {
    id: id,
    method: function(params) {
      doSomething(params);
    }
  };
};

欢迎对此解决方案提出意见和建议。:)

西里Near 2020.03.30

是的,您可以在类声明中定义一个构造函数,如下所示:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Tony凯 2020.03.30

那么“构造函数”属性的意义是什么?无法找出在哪里有用的任何想法?

构造器属性的要点是提供某种方式来假装JavaScript具有类。无法做的一件事是在创建对象后更改对象的构造函数。情况很复杂。

几年前,我在上面写了一篇相当全面的文章:http : //joost.zeekat.nl/constructors-considered-mildly-confusing.html

古一 2020.03.30

这是一个构造函数:

function MyClass() {}

当你做

var myObj = new MyClass();

MyClass 执行,并返回该类的新对象。

宝儿 2020.03.30

使用原型:

function Box(color) // Constructor
{
    this.color = color;
}

Box.prototype.getColor = function()
{
    return this.color;
};

隐藏“颜色”(有点像私有成员变量):

function Box(col)
{
   var color = col;

   this.getColor = function()
   {
       return color;
   };
}

用法:

var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue

var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android