Javascript 如何在不使用new关键字的情况下设置原型函数
在原型继承的一个简单示例中,我想将Javascript 如何在不使用new关键字的情况下设置原型函数,javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,在原型继承的一个简单示例中,我想将Person对象设置为Student对象的父类,但我不想在为Student类设置原型时使用new关键字,因为这是错误的。但不知怎么的,这个代码不起作用。有什么帮助吗 var Person = function(name) { var that = this; this.name = name; var _log = function() { console.log("Hello", that.name) }; return {
Person
对象设置为Student
对象的父类,但我不想在为Student
类设置原型时使用new关键字,因为这是错误的。但不知怎么的,这个代码不起作用。有什么帮助吗
var Person = function(name) {
var that = this;
this.name = name;
var _log = function() {
console.log("Hello", that.name)
};
return {
log: _log
};
};
var Student = function(name) {
Person.call(this, name);
var _getCollegeName = function() {
console.log("MIT")
};
return {
getCollegeName: _getCollegeName
};
};
Student.prototype = Object.create(Person);
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class
var s = new Student("Soham");
s.log();
//s.getCollegeName();
您可以将
getCollegeName
设置为Person()
调用、返回Person
对象的属性
var Person=函数(名称){
var=这个;
this.name=名称;
var_log=函数(){
log(“Hello”,即.name)
};
返回{
日志:\u日志
};
};
var Student=函数(名称){
var p=Person.call(这个,名字);
var_getCollegeName=函数(){
console.log(“MIT”)
};
p、 getCollegeName=\u getCollegeName;
返回p
};
Student.prototype=Object.create(Person);
//Student.prototype=新人(“Soham”);希望避免这种情况,因为值应该从子类传递
var s=学生(“Soham”);
s、 log();
s、 getCollegeName()代码>即使我使用Student.prototype=newperson(“Soham”)
而不是对象,代码也不起作用。create