Javascript继承和;这";及;那";
我有一个类,我使用它的方法作为事件监听器,所以我在方法中不使用Javascript继承和;这";及;那";,javascript,class,inheritance,this,Javascript,Class,Inheritance,This,我有一个类,我使用它的方法作为事件监听器,所以我在方法中不使用this,而是使用that 这是基类: function Modal(){ var that = this; this.opened = false; this.open = function(){ that.opened = true; var id = this.id; // more code }; this.close =
this
,而是使用that
这是基类:
function Modal(){
var that = this;
this.opened = false;
this.open = function(){
that.opened = true;
var id = this.id;
// more code
};
this.close = function () {
if (that.opened) // do something;
};
}
这是继承的类:
function ModalBook(){
var that = this;
this.open = function(){
that.opened = true;
var id = this.id;
// more code
};
}
ModalBook.prototype = new Modal();
var modalBook = new ModalBook();
现在,打开模式时,modal.opened
的值为true,但关闭模式时,该值为false
在this.close
行上调试时,我看到那是Modal
的一个实例,modalBook
那是modalBook
的一个实例
因此,我的问题是:如何在modalBook
的两种方法中保留this
的值?在modalBook.prototype=new Modal()
modalBook
中发生的事情是“继承”Modal
。变量在其作用域中属于每个构造函数,属性被覆盖。因此:
在模式中的
将在本地停留在模式中
在ModalBook
中的将是ModalBook
- 但是唯一存在的
open()
方法是ModalBook.open()
(您正在覆盖另一个方法),其中是ModalBook
的一个实例,而另一个不在该范围内
我想你的设计有问题。可能会使用不同名称的属性来解决问题
行ModalBook.prototype=new Modal()
表示所有新的ModalBook指向一个单一的新模态对象,该模型对象是close方法中的
不会为每个新的ModalBook
重新创建此对象。这是原型继承
修复
如果操作正确,则无需捕获此
传统上,这里有一种更好的编码方法
var Modal = function(){ return this; };
Modal.prototype = {
opened : false,
open : function(){
this.opened = true;
var id = this.id;
// more code
},
close : function () {
if (this.opened) // do something;
},
};
// Old IE may not have Object.assign or Object.create. shims available.
var ModalBook = function(){ Modal.call( this ); return this; };
ModalBook.prototype = Object.assign( Object.create( Modal.prototype ), {
open : function(){
this.opened = true;
var id = this.id;
console.log( 'open2' );
}
} );
var modalBook = new ModalBook();
无构造函数
或者如果你不喜欢使用构造函数,就像我一样
/* In ES6. Runs on Chrome, Firefox, Edge, Safari. Use Babel to run on IE. */
const Modal = {
opened: false,
create () { return Object.create( Modal ).initialise(); },
initialise () { return this; },
open () { /* ... */ },
close () { /* ... */ },
};
const ModalBook = {
__proto__ : Modal,
create () { return Object.create( ModalBook ).initialise(); },
open () { /* ... */ },
};
var modalBook = ModalBook();
你能为这个做一把小提琴吗?