我正在尝试更好地理解javascript中的继承。我的目标是编写一个函数来声明一些变量并设置一个环境,以便其他函数可以构建它。我有点像Ruby中的mixins一样思考。这是一个不起作用的简单示例。
function baseFunction(){
this.my_var = "hello world";
};
function speakMessage(){
alert(this.my_var);
}
speakMessage.prototype = baseFunction();
speakmessage();
我想如果我设置baseFunction原型,那么将在baseFunction中搜索speakMessage函数中找不到的任何属性。那不对吗?我是如何让这个工作的?
答案 0 :(得分:4)
琐碎的答案,但...... speakMessage();
(大M): - )
Javascript区分大小写。
我错过了HMR的好评:如果在Javascript中与 new 一起使用,函数就像构造函数一样。请注意我添加到您的代码中的两个new
:
my_var = "goodbye world";
function baseFunction() {
this.my_var = "hello world";
}
function speakMessage() {
alert(this.my_var);
}
speakMessage.prototype = new baseFunction(); // new: inherit from object
new speakMessage(); // object constructor: hello world
speakMessage(); // function: goodbye world from window object context
另请参阅HMR的答案。
答案 1 :(得分:2)
微小的错误。你打电话给 m 消息();当你创建函数时,请说出 M 这应该修复它。
function baseFunction(){
this.my_var = "hello world";
};
function speakMessage(){
alert(this.my_var);
}
speakMessage.prototype = baseFunction();
speakMessage();
答案 2 :(得分:2)
对于未来的绊脚石;之前给出的答案只能解决OP问题中的拼写错误。至于speakMunction继承自baseFunction,OP的代码是完全错误的,应该/看起来像这样:
(请注意,构造函数应以大写字母开头)
function BaseFunction(args){
//name is instance specific
//defaults to World
this.name = (args&&args.name)?args.name:"World";
};
//shared members
BaseFunction.prototype.saySomething=function(){
return "From BaseFunction:"+this.name;
};
function SpeakMessage(args){
//re use BaseFunction constructor code
BaseFunction.call(this,args);
}
//inherit shared members from prototype
SpeakMessage.prototype = Object.create(BaseFunction.prototype);
//repair built in constructor value (or it'll point to BaseFunction)
SpeakMessage.prototype.constructor=SpeakMessage;
//extend saySomething, this is optional an shows how
// to add extra functionality to existing Parent functions
SpeakMessage.prototype.saySomething=function(){
return BaseFunction.prototype.saySomething.call(this) +
", from SpeakMessage:"+this.name;
};
var world = new SpeakMessage();//defaults name to be "world"
//following will output: From BaseFunction:World, from SpeakMessage:World
console.log(world.saySomething());
var op = new SpeakMessage({name:"OP"});
//following will output:From BaseFunction:OP, from SpeakMessage:OP
console.log(op.saySomething());
var parent = new BaseFunction();
console.log(parent.saySomething());//=From BaseFunction:World
与评论一样;有关构造函数和原型的更多信息:https://stackoverflow.com/a/16063711/1641941
关于提到封闭的评论;你可以使用闭包而不是构造函数来处理更简单的对象:
var baseFunction=function(message){
return function(){
console.log("Hello "+message);
};
}
var world = baseFunction("World");
var op = baseFunction("OP");
world();//=Hello World
op();//=Hello OP
有关闭包的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures