在继承原型JS时传递参数可以通过以下几种方式实现:
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
var child = new Child("John", 10);
console.log(child.name); // 输出 "John"
console.log(child.age); // 输出 10
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log("Hello, " + this.name);
}
function Child(name, age) {
var child = Object.create(Parent.prototype);
child.name = name;
child.age = age;
return child;
}
var child = Child("John", 10);
console.log(child.name); // 输出 "John"
console.log(child.age); // 输出 10
child.sayHello(); // 输出 "Hello, John"
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
var child = new Child("John", 10);
console.log(child.name); // 输出 "John"
console.log(child.age); // 输出 10
以上是在继承原型JS时传递参数的几种常见方式。根据具体的需求和场景选择适合的方式进行参数传递。腾讯云提供的相关产品和服务可以参考腾讯云官方文档:腾讯云产品与服务。
领取专属 10元无门槛券
手把手带您无忧上云