JavaScript继承

发布时间:2026/8/1 19:08:35
JavaScript继承 函数原型对象冒充实现继承// 父类函数functionPerson(name){this.namename;}// 父类函数的原型属性Person.prototype.sayfunction(){console.log(Hello this.name);};// 子类函数functionNinja(name,weapon){// 对象冒充将子类函数的上下文this,传给父类构造函数这样可以实现将父类函数的属性挂载到子类对象中// 这样就可以使用子类函数构造器将父类函数的属性copy过来。见下图Person.call(this,name);this.weaponweapon;}// 为了继承父类原型上的方法我们知道每个构造函数的实例有含有一个指向原型的引用//而js查找标识符属性或方法是在原型链上由近及远搜索Ninja.prototypenewPerson();Ninja.prototype.feintfunction(){console.log(feint using this.weapon);};// 将Ninja.prototype替换为Person实例会让prototype少一个constructor属性这里使用Object内置的方法设置constructor// 详见Object.defineProperty说明Object.defineProperty(Ninja.prototype,constructor,{enumerable:false,value:Ninja,writable:true});// 你也可以简单地这样做效果和上面一样。// Ninja.prototype Object.create(Person.prototype);// Ninja.prototype.constructor Ninja;letninjanewNinja(YouShi,Knife);ninja.say();ninja.feint();Chrome的scope视图运行结果原理说明