我可以在js中通过父对象创建一个对象吗

Can i create an object trough parent in js

本文关键字:对象 创建 一个对象 js 我可以      更新时间:2023-09-26

我是OOJS的新手,在理解继承时有点困惑,我创建了两个简单的类,person和student,它们从person继承,有没有通过在父的构造函数中传递数据来创建student的选项?如果可能的话,怎么做?子级是否可以从父级获取所有属性和方法,或者只获取方法?

**警报中的fname和lName是未定义的

function Person(fNme, lName) {
                this.fname = fNme;
               this.lName = lName;
               } 
               Object.prototype.go = function() {
                 alert("I am going now last time you see  "+ this.lName);
            }
            function Student() {
                this.study = function () {
                   alert("I am studing !");
                }
            }
            Student.prototype = new Person();
            var s1 = new Student("sam", "bubu");
            alert(s1.fname +"+"+ s1.lName)   

您可以使用构造函数窃取。

  function Student(fName,lName) {
      Person.call(this,fName,lName); 
                this.study = function () {
                   alert("I am studing !");
                }
            }

当调用Student构造函数时,可以将参数传递给Person()call(),以初始化Person 中的变量

只需调用父构造函数

function Student(fName, lName, whateverelse) {
     Person.call( this, fName, lName ); // call base class constructor function
     this.study = function () {
        alert("I am studing !");
     }
}