gpt4 book ai didi

javascript - 创建一个类,从另一个扩展并调用父方法

转载 作者:行者123 更新时间:2023-11-29 16:17:18 24 4
gpt4 key购买 nike

首先,我从 coffeescript 站点获取了动物示例。

我想在 javascript 中模拟接下来的事情:

  • 类(class)
  • 仅限公共(public)方法
  • 仅限私有(private)方法和变量
  • 继承
  • 从父类(super class)中调用方法

我认为这种创建方式是可以的,但是当我尝试从父类中获取move 方法时,它总是返回到自身。我做错了什么?

顺便说一句。哪些是实现我的目标的最佳实践?我的做法对吗?

var Animal = (function() {
function Animal() {}

var _private = {};
var _public = {
move: function() {
console.log('Can move');
}
};

Animal.prototype = _public;
Animal.prototype.constructor = Animal;
return Animal;
})();

var Snake = (function(_super) {
function Snake() {}

var _private = {};
var _public = {
move: function() {
console.log(Snake._super_.move);
console.log('Slithering');
}
};

Snake.prototype = _super.prototype;
Snake._super_ = _super.prototype;
for(var method in _public) {
if(Object.prototype.toString.call(_public[method]) === '[object Function]') {
Snake.prototype[method] = _public[method];
}
}
return Snake;
})(Animal);

var s = new Snake;
s.move();

最佳答案

在我看来,这段代码写得非常好,只有一个小错误。

我觉得你的指点有点不对,试试这个:

<script>
var Animal = (function () {
function Animal() { }

var _private = {};
var _public = {
move: function () {
console.log('Can move');
//this just returns a string to show which method was called
//inside of the child's move function's console.log
return "super move called";
}
};

Animal.prototype = _public;
Animal.prototype.constructor = Animal;
return Animal;
})();

var Snake = (function (_super) {
function Snake() { }

var _private = {};
var _public = {
move: function () {
console.log(Snake._super_.move());//Now we can call super's move
console.log('Slithering');
}
};

//This created the circular reference where Snake._super_ was pointing to
//Snake.prototype which was causing the error
//Snake.prototype = _super.prototype;
Snake._super_ = _super.prototype;

for (var method in _public) {
if (Object.prototype.toString.call(_public[method]) === '[object Function]') {
Snake.prototype[method] = _public[method];
}
}
return Snake;
})(Animal);

var s = new Snake;
s.move();//now this outputs "Can move", "super move called", "Slithering"
</script>

关于javascript - 创建一个类,从另一个扩展并调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com