아래 코드에서 Mass
생성자 및 일부 메서드가 있습니다. 원래 메서드는 Mass
생성자 안에 있었지만 사용중인 메서드가 많이 있습니다. 그래서, 좀 더 체계화 된 것을 유지하기 위해서, 나는 Mass
외부의 몇몇 메소드를 제거하고 프로토 타입을 사용하여 추가했습니다.프로토 타입 메서드에서 액세스 생성자
하지만 문제가 있습니다. 나는 Mass
을 this
으로 언급 할 수 없다. 그것은 window
을 말합니다.
function Mass(elm) {
this.getElement = function(element) {
if (typeof element == "string") {
return document.getElementById(element);
}
return element;
};
this.elm = this.getElement(elm);
this.elm.style.position = "absolute";
this.elm.style.left = 0 + "px";
this.elm.style.top = 0 + "px";
this.updateVars = function() {
this.width = parseInt(this.elm.style.width, 10);
this.height = parseInt(this.elm.style.height, 10);
this.top = parseInt(this.elm.style.top, 10);
this.left = parseInt(this.elm.style.left, 10);
this.radius = this.width/2;
this.originX = this.left + this.radius;
this.originY = this.top + this.radius;
this.worldOrgX = this.originX + parseInt(this.elm.parentNode.style.left, 10);
this.worldOrgY = this.originY + parseInt(this.elm.parentNode.style.top, 10);
};
}
Mass.prototype = {
// other methods here
rotation : {
// this = window
mass : this,
angle : 0,
handler : null,
rotate : function (angularVelocity, rotationSpeed) {
this.angle = (this.angle + angularVelocity) % 360;
// here I need to access Mass.elm and apply rotate
this.mass.elm.style.webkitTransform = "rotate(" + this.angle + "deg)";
},
start : function (angularVelocity, rotationSpeed) {
var rotation = this; // this = Mass.rotation
rotation.handler = setInterval(function() {
rotation.rotate(angularVelocity, rotationSpeed);
}, rotationSpeed);
},
},
}
var earth = new Mass("earth");
//earth.rotation.start(4.5, 25);
이 잘 노력하고 있습니다. 새로운 제품을 만들기 위해서는 어떤 변화를 가져야합니까?
[JavaScript 프로토 타입 기능에서 "this"에 대한 참조를 유지함] (http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript) -prototype-functions). –
그 순간에 인스턴스를 만들지 않았다면 '이'가 '미사'의 인스턴스를 나타낼 것이라고 생각하게 만들었습니까? 'this'는별로 복잡하지 않습니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this –
@PM 약간 다른 문제입니다. 질량에는 회전과 연산이 있습니다. 회전에서 매스 인스턴스를 알아야합니다. 이 회전의 값은 회전 (호출하는 객체)이 될 것이지만 op는 거기에서 Mass 인스턴스를 얻는 방법을 모릅니다. – HMR