Danack / PHP-to-Javascript

A tool for converting simple PHP objects/code to Javascript, so that code for manipulating objects can be used both server-side and client-side.
Other
104 stars 32 forks source link

var as local variable #45

Closed ghost closed 11 years ago

ghost commented 11 years ago

var is useful keyword in js. see

function Foo{
    var self;
    function testFunctionStatic(){}
    this.anonymusFunction(){
        alert(self.foo)
    }
    /* constrructor on end of code */
    self = this;
    this.foo="aloha";
    this.testFunc();
    window.onbeforeunload = this.anonymusFunction;
}

I think php var, like

class Foo{
    var $self;
}
Danack commented 11 years ago

The idea of this project is to convert PHP into equivalent Javascript. If you then need to do extra stuff in Javascript e.g. like binding objects to events, you should do that in a separate Javascript file that does the binding of the Javascript converted from PHP to the events.

However even if you really do want to do it all in one file, there's a better way of doing it. Using the:

$phpToJavascript->addPostConversionReplace("//JS", "");

To allow us to insert actual Javscript into the PHP, we can do:

class TestClass {

    public $message;

    function __construct($message) {
        $this->message = $message;
    }

    function windowCloseFunction() {
        echo "Goodbye ".$this->message;
    }

    //If you have jQuery 
    //JS window.onresize = $.proxy(this, 'windowCloseFunction');

    //Or with standard Javascript
//    //JS this.makeWindowCloseFunction = function($context, $functionName) {
//    //JS    return function() {
//    //JS        $functionName.call($context);
//    //JS    }
//    //JS}
//    //JS
//    //JS window.onresize = this.makeWindowCloseFunction(this, this.windowCloseFunction);
}

$test = new TestClass("cruel world!");

I know that a lot of tutorial say to use a var to save the current context - I'm pretty sure that's a bad idea.